$(document).ready(function () {
    
    /* Position subnav divs */
    $('div#subnav div').each(function () {
        var tab = $('div#nav a[href='+this.id+']');
        var taboffset = tab.offset().left;
        var subnavoffset = $(this).parent().offset().left;
        var subnavwidth = $(this).parent().width();
        var maxOffset = taboffset - subnavoffset;
        if (maxOffset !== 0) { maxOffset -= 2; } /* this fixes subnav alignment in FF3, does it break ie? */
        if (maxOffset > subnavwidth - $(this).width()) { 
            maxOffset = subnavwidth - $(this).width();        
        }
        if (this.id == '/index/links/') {
            maxOffset -= 80;
        }
        $(this).css({display: 'block'});
        if (!$(this).is('.selected')) {
            $(this).css({opacity: 0, zIndex: -1});        
            $(this).css({left: maxOffset});
        } else {
            $(this).animate({left: maxOffset}, 400);        
        }
    });
    /* search box auto-value */
    $('input#site_search').focus(function () {
        if (this.value == 'CZ Search') {
            this.value = '';        
        }
    }).blur(function () {
        if (this.value === '') {
            this.value = 'CZ Search';        
        }
    });
    
    /* Main nav hover evect */
    $('div#nav a').hover(function () {
        var divid = $(this).attr('href');
        $(this).parent().children().each(function () { $(this).removeClass('hover'); });
        $(this).addClass('hover');
        /* show the appropriate subnav div, and hide the rest. */
        $("div#subnav div").each(function () { 
            if (this.id != divid) { 
                $(this).fadeTo('fast', 0); 
                $(this).css('zIndex',-1);
            } else {
                $(this).fadeTo('fast', 1);
                $(this).css('zIndex',1);
            }
        });        
    });
    /* Hover evect for subnav */
    $('div#subnav a img').hover(function (event) {
        $(this).fadeTo('fast', 1);
        event.stopPropagation();
    }, function (event) {
        if (!$(this).parent().is('.selected')) {
            $(this).fadeTo('fast', 0.4);
        }
        event.stopPropagation();
    });
    
    /* revert to the selected nav item when they leave the main nav container */
    $('div#nav-container').mouseleave(function () { 
        $("div#nav a").removeClass('hover');
        $("div#subnav div").each(function () { 
            if ($(this).is('.selected')) { 
                $(this).css({zIndex:1}).fadeTo('fast', 1); 
            } else {
                $(this).css({zIndex:0}).fadeTo('fast', 0);
            }
        }); 
        return false;
    });
    /* Catch the enter event of other containers incase the browser doesn't register the above. */
    $("div#search-bar, div#body").mouseenter(function () {
        $('div#nav-container').mouseleave();
    });
    
    
    function findValue(li) {
            if( li === null ) { return alert("No match!"); }   
            window.location = "/products/view/" + li.extra[3] + "/";
    }    
    function selectItem(li) {
            findValue(li);
    }
    
    function sformatItem(row) {
        var qs = $('#product_search_autocomplete').val();
        html = "<img src='"+row[3]+"' alt='product_image' /><div>"+row[0].replace( new RegExp('('+qs+')','ig'), '<b>$1</b>')+"</div><div class='clear'></div>";
        return html;
    }       
    
    function ssFindValue(li) {
            if( li === null ) { return alert("No match!"); }   
            alert("product " +  li.extra[0] + ".");
    }    
    function ssSelectItem(li) {
            ssFindValue(li);
    }
    
    
    $("#product_search_autocomplete").autocomplete(
                "/product-search-ajax/",
                {
                        delay:10,
                        minChars:1,
                        cacheLength:5,
                        matchContains: true,
                        onItemSelect:selectItem,
                        onFindValue:findValue,
                        formatItem:sformatItem,
                        autoFill:false,
                        maxItemsToShow: 20
                }
        );
    $('#site_search').autocomplete(
        "/search-suggestions/",
        {
            delay: 10,
            minChars: 2,
            cacheLength: 0,
            matchContains: true,
            onItemSelect: ssSelectItem,
            onFindValue: ssFindValue,
            autoFill: false,
            maxItemsToShow: 5
        }
    );
    $('#zip_code_box').focus(function () {
        if ($(this).val() == "Zip Code") {
            $(this).val("");        
        }
        
    }).blur(function () {
        if ($(this).val() === "") {
            $(this).val("Zip Code");        
        }
    });
    $('select#browse_by').change(function () {
        var bb = $(this).val();
        window.location = "/products/"+bb+"/";
    });
    $('select#root').change(function () {
        var bb = $('select#browse_by').val();
        var root = $(this).val();
        window.location = "/products/"+bb+"/"+root+"/";
    });
    $('select#subitem').change(function () {
        var bb = $('select#browse_by').val();
        var sub = $(this).val();
        window.location = "/products/"+bb+"/"+sub+"/";
    });
    if (location.hash.match(/^#m\d+$/)) {
        var selector = "a[name='"+location.hash.substring(1)+"']";
        var el = $(selector);
        
    }
    $('div.media_coverage div.page-title').click(function () { $(this).next().slideToggle(); });
    $('div.press-releases div.page-title').click(function () { $(this).next().slideToggle(); });
     function findProduct(li) {
            if( li === null ) { return alert("No match!"); }   
            $('#id_product').val(li.extra[0]);
    }    
    function formatItem(row) {
        var qs = $('#id_product_selector_autocomplete').val();
        var html = "<img src='"+row[3]+"' /><div>"+row[0].replace( new RegExp('('+qs+')','ig'), '<b>$1</b>')+"<br /><span class='autocomplete_details'>"+row[2]+"</span></div><div class='clear'></div>";
        return html;
    }
    $("#id_product_selector_autocomplete").autocomplete(
                "/product-search-ajax/",
                {
                        delay:10,
                        minChars:2,
                        cacheLength:5,
                        matchContains: true,
                        onItemSelect:findProduct,
                        onFindValue:findProduct,
                        formatItem:formatItem,
                        autoFill:false,
                        maxItemsToShow: 20
                }
    );

    bindToSubmissionForm = function () {
        $('#id_image').parent().hide();
        $('#id_video_embed').parent().hide();
        $('#id_type').change(function () {
            if (this.value == 'S') {
                $('#id_image').parent().hide();
                $('#id_video_embed').parent().hide();
            } else if (this.value == 'P') {
                $('#id_image').parent().show();
                $('#id_video_embed').parent().hide();
            } else if (this.value == 'V') {
                $('#id_image').parent().hide();
                $('#id_video_embed').parent().show();
            }
        });
        $('#id_type').change();
        $('#question_form').submit(function () { 
            var data = $(this).serialize();
            var ct = $('#id_content_type').val();
            var pk = $('#id_object_id').val();
            $('#form_placeholder').html("<div style='text-align:center'><img src='/assets/i/ajax-loader.gif' /></div>");
            $.post('/questions/?ct=' + ct + '&pk=' + pk,
                    data,
                    function (data) { 
                        $('#form_placeholder').html(data);
                    });
            return false;        
        });
        /* $('#story_form').submit(function () { 
            var data = $(this).serialize();
            var ct = $('#id_content_type').val();
            var pk = $('#id_object_id').val();
            $('#form_placeholder').html("<div style='text-align:center'><img src='/assets/i/ajax-loader.gif' /></div>");
            $.post('/user-submission/?ct=' + ct + '&pk=' + pk,
                    data,
                    function (data) { 
                        $('#form_placeholder').html(data);
                    });
            return false;        
        }); */

    };
    
    $('a.get_more_submissions').click(function () {
        var s = $(this).attr('rel');
        var ct = s.split(";")[0];
        var pk = s.split(";")[1];
        var o = s.split(";")[2];
        url = '/submissions/?ct=' + ct + '&pk=' + pk + '&o=' + o;
        $.get(url, {}, function (data, status) {
            for (var i = 0; i<data.submissions.length;i++) {
                var el = data.submissions[i].toString();
                $('ul.user-submissions').append(el);            
            }
            if (data.more) {
                $('a.get_more_submissions').attr('rel',''+ct+';'+pk+';'+data.offset+'');
            } else {
                $('a.get_more_submissions').remove();  
            }
        }, 'json')
        return false;
    }).click();
    
    $('.question_link').click(function () {
        var info = $(this).attr('rel');
        var ct = info.split(';')[0];
        var pk = info.split(';')[1];
        $('#form_placeholder').html("<div style='text-align:center'><img src='/assets/i/ajax-loader.gif' /></div>");
        $.get('/questions/?ct=' + ct + '&pk=' + pk,
              {}, 
              function (data, status) {
                  document.getElementById('form_placeholder').innerHTML = data;
                  bindToSubmissionForm();
                  return false;  
              }, 'html');
        return false;


    });
    
    $('.submission_link').click(function () {
        var info = $(this).attr('rel');
        var ct = info.split(';')[0];
        var pk = info.split(';')[1];
        $('#form_placeholder').html("<div style='text-align:center'><img src='/assets/i/ajax-loader.gif' /></div>");
        $.get('/user-submission/?ct=' + ct + '&pk=' + pk,
              {}, 
              function (data, status) {
                  document.getElementById('form_placeholder').innerHTML = data;
                  /* $('#form_placeholder').html(data.toString());    */
                  bindToSubmissionForm();
                  return false;  
              }, 'html');
        return false;
    });
    $('.newsletter_link').click(function () {
        $('#newsletter_subscribe_form').toggle();    
        return false;
    });
});

