$(document).ready(function(){

    var scrollSpeed = 300; // in milliseconds. used to be 100

    // disable aloha's error handling
    if (window.GENTICS) {
        window.GENTICS.Aloha.settings.errorhandling = false;
        window.GENTICS.Aloha.settings.logLevels = {
            error: false,
            warn: false//,
            //info: true//,
            //debug: true
        };
    }

    /*
    $('.page-header').each(function() {
        $(this).height($(this).height());
    });
    */

    // These functions are from underscore.js:
    // http://documentcloud.github.com/underscore/
    // Internal function used to implement `_.throttle` and `_.debounce`.
    var limit = function(func, wait, debounce) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var throttler = function() {
                timeout = null;
                func.apply(context, args);
            };
            if (debounce) clearTimeout(timeout);
            if (debounce || !timeout) timeout = setTimeout(throttler, wait);
        };
    };
    // Returns a function, that, when invoked, will only be triggered at most
    // once during a given window of time.
    var throttle = function(func, wait) {
        return limit(func, wait, false);
    };
    // Returns a function, that, as long as it continues to be invoked, will
    // not be triggered. The function will be called after it stops being
    // called for N milliseconds.
    var debounce = function(func, wait) {
        return limit(func, wait, true);
    };

    // Nav bar scrolling
    // =================

    var nav = $('ul.nav-primary li > a').filter(function() {
            // only links that point to elements
            var href = $(this).attr('href');
            return (href[0] == '#' && $(href).length);
        }),
        targets = nav.map(function() {
            // array of jquery selectors
            return $(this).attr('href');
        });

    var scrollTo = function(where) {
        if (where && where[0] == '#' && $(where).length) {
            var t;
            if (where == '#hero') {
                t = 0;
            } else {
                t = $(where).offset().top-$('header').outerHeight();
            }
            console.log("going to", t);
            $('html,body').animate({scrollTop : t}, scrollSpeed);
        }
    };

    nav.add('.scrollto').click(function(event) {
        event.preventDefault();
        event.stopPropagation();

        var href = $(this).attr('href');
        scrollTo(href);
    });

    //var cancelHashJump = false;

    var processScroll = function() {
        //cancelHashJump = true;

        var offsets = $.map(targets, function(id) {
            // array of positions for targets
            if (id == '#hero') {
                return 0;
            }
            return $(id).offset().top;
        });
        var windowTop = $(window).scrollTop()+$('#header').outerHeight();
        //console.log("current scroll position:", windowTop);
        for (var i=offsets.length-1; i>=0; i--) {
            var currentNav = nav.eq(i),
                currentOffset = offsets[i],
                currentTarget = targets.eq(i);

            //console.log("checking", currentTarget, currentOffset);
            if (windowTop >= offsets[i] &&
                    (!offsets[i+1] || windowTop <= offsets[i+1])) {
                $('ul.nav-primary li').removeClass('active');
                currentNav.parents('li').addClass('active');
                return;
            }
        }
        // if we made it here just hide them all.
        $('ul.nav-primary li').removeClass('active');
    };

    /*
    if (window.location.hash) {
        // the window is still load loading, so sizes are still changing.
        // wait for all that to end
        $(window).load(function() {
            // don't scroll automatically if the user scrolled manually.
            if (!cancelHashJump) {
                scrollTo(window.location.hash);
            }
        });

    } else {
        processScroll();
    }
    */
    processScroll();


    $(window).scroll(throttle(function() {
        processScroll();
    }, 100));


    // Dropdown example for topbar nav
    // ===============================

    $("body").bind("click", function(e) {
        $('.dropdown-toggle, .menu').parent("li").removeClass("open");
    });
    $(".dropdown-toggle, .menu").click(function(e) {
        var $li = $(this).parent("li").toggleClass('open');
        return false;
    });

    // add on logic
    // ============

    /*
    $('.add-on :checkbox').click(function() {
        if ($(this).attr('checked')) {
            $(this).parents('.add-on').addClass('active');
        } else {
            $(this).parents('.add-on').removeClass('active');
        }
    });
    */

    // Disable certain links in docs
    // =============================

    $('ul.tabs a, ul.pills a, .pagination a, .well .btn, .actions .btn, .alert-message .btn, a.close').click(function(e) {
        e.preventDefault();
    });

    // Copy code blocks in docs
    $(".copy-code").focus(function() {
        var el = this;
        // push select to event loop for chrome :{o
        setTimeout(function() { $(el).select(); }, 1);
    });

    // Get Skeleton Tabs Activiation
    // =============================

    var tabs = $('ul.tabs');

    tabs.each(function(i) {

        //Get all tabs
        var tab = $(this).find('> li > a');
        tab.click(function(e) {

            //Get Location of tab's content
            var contentLocation = $(this).attr('href');

            //Let go if not a hashed one
            if (contentLocation.charAt(0) == "#") {
                e.preventDefault();

                // Make Tab Active
                tab.removeClass('active');
                $(this).addClass('active');

                // Show Tab Content & add active class
                $(contentLocation).show().addClass('active')
                    .siblings().hide().removeClass('active');

                // workaround for bug where codemirror doesn't display properly
                var codemirror = $(contentLocation).find('#csseditor');
                if (codemirror.length) {
                    var codeEd = codemirror.data('codeEd')
                    codeEd.refresh();
                }
            }
        });
    });

    // GEO PRICING
    // ===========

    var setCookie = function(name, value, exdays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var value = escape(value);
        if (exdays !== null) {
            value = value + "; expires="+exdate.toUTCString();
        }
        document.cookie = name + "=" + value;
    };
    var getCookie = function(name) {
        var i, x, y,
            ARRcookies = document.cookie.split(";");
        for (i=0; i<ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
            x = x.replace(/^\s+|\s+$/g,"");
            if (x == name) {
                return unescape(y);
            }
        }
        return null;
    };
    var checkCountry = function() {
        var country = getCookie('country');
        if (country) {
            setCountry(country);
        } else {
            var geourl = "http://www.geoplugin.net/json.gp?jsoncallback=?";
            $.getJSON(geourl, function(data) {
                if (data['geoplugin_countryCode']){
                    var country = data['geoplugin_countryCode'];
                    if (country) {
                        setCookie('country', country);
                        setCountry(country);
                    }
                }
            });
        }
    };
    var setCountry = function(country) {
        if (country.toLowerCase() == 'za') {
            $('body').addClass('local');
        } else {
            $('body').addClass('international');
        }
    };
    checkCountry();

    var isTouchDevice = function() {
        try {
            document.createEvent("TouchEvent");
            return true;
        } catch(e) {
            return false;
        }
    };
    var isMobileOS = function() {
        // you can't just go on touch event support,
        // codemirror doesn't actually use contenteditable,
        // checks for contenteditable gives false positives
        if (navigator.userAgent.match(
                /(iPod|iPhone|iPad|Android|WebOS|Blackberry)/i)) {
            return true;
        } else {
            return false;
        }
    };

    // CODEMIRROR
    // ==========

    if (window.CodeMirror) {

        var lazyOnChange = debounce(function(editor) {
            var css = editor.getValue();
            $('#customcss').replaceWith(
                '<style id="customcss">'+css+'</style>');
        }, 500);

        if (!isMobileOS()) {
            $('#csseditor').html('');

            $('head').append('<style id="customcss"></style>');

            var hlLine;
            var codeEd = CodeMirror($('#csseditor')[0], {
                onChange: lazyOnChange,
                value: "/* If you know CSS this is the place to show it off */\n"+
                       "body {\n"+
                       "    background-color: #fff;\n"+
                       "    color: #404040;\n"+
                       "}\n",
                mode: "css",
                indentUnit: 4,
                tabMode: 'shift',
                lineNumbers: true,
                gutter: true,
                matchBrackets: true,
                onCursorActivity: function() {
                    codeEd.setLineClass(hlLine, null);
                    hlLine = codeEd.setLineClass(
                        codeEd.getCursor().line, "activeline");
                }
            });
            hlLine = codeEd.setLineClass(0, "activeline");
            $('#csseditor').data('codeEd', codeEd);
        }
    }

    // WIG
    // ===
    if ($.fn.wig) {
        if (!isMobileOS() && $('.editable')[0].contentEditable != null) {
            $('.editable-disabled').hide();
            $('.editable').show();
            $('.editable').wig({'validImageDomains': []});
        } else {
            $('.editable-disabled').show();
            $('.editable').hide();
        }
    }

    // UPGROUPER
    // =========

    if (window.Upgrouper) {
        var Importer = window.upgrouper = jQuery.extend(
            true, {}, Upgrouper);

        // For the demo we don't actually upload anything
        Importer.uploadUrl = '/';
        Importer.groupableSortableSettings.handle = 'img,.no-image';
        Importer.groupableSortableSettings
        // a sortable container of images (as part of noun-number id="")
        Importer.groupingNoun = 'imagegrid';
        // a product image (as part of noun-number id="")
        Importer.groupableNoun = 'image';
        // a sortable container of images
        Importer.groupingSelector = '.imagegrid';
        // a product image
        Importer.groupableSelector = '.image';
        // all the places where you can drop new images
        Importer.groupingDroppableSelector = '#dropzone';
        Importer.previewSize = '154W';

        var loadGroupableImage = function($groupable, file) {
            var reader = new FileReader();
            reader.onload = function(event) {
                var img = $('<img src="'+event.target.result+'" width="154">');
                $groupable.find('.no-image,img').replaceWith(img);
            };
            reader.readAsDataURL(file);
        };

        Importer.filesDropped = function(
                grouping, groupables, files, isNewGrouping) {
            var groupable, file, del;

            for (var i=0; i<groupables.length; i++) {
                groupable = groupables[i];
                file = files[i];
                var $groupable = $(groupable);

                if (typeof window.FileReader === 'undefined') {
                    // fail
                    $(groupable).find('.no-image').append(
                        '<div class="unsupported">Real image uploads are disabled for this demo. Try Chrome or Firefox for live previews.</div>');
                } else {
                    // working
                    loadGroupableImage($groupable, file);
                }

                // make it deletable
                del = $('<div class="delete" title="Delete">Delete</div>');

                $groupable.append(del);

                $groupable.find('.progress .inner').html('done');
                $groupable.find('.progress').hide();

                $groupable.removeClass('in-progress');
            }

            Importer.syncGroupingEnabled($(grouping));
        };

        Importer.getImage = function(json) {
        };

        Importer.addGroupableInfo = function(file, groupable, json) {
        };

        Importer.notSupported = function() {
            $('#dropzone').addClass('upgrouper-disabled');
        };

        $('#dropzone').removeClass('upgrouper-disabled');

        Importer.init();

        $('input[name=files]').change(function() {
            Importer.handleDropped($('#dropzone'), this.files);
        });

        var deleteImage = function() {
                var image = $(this).parents('.image');
                Importer.confirmDeleteGroupable(image);
            },
            confirmDeleteImage = function() {
                var image = $(this).parents('.image');
                image.remove();
            },
            cancelDeleteImage = function() {
                var image = $(this).parents('.image');
                Importer.cancelDeleteGroupable(image);
            },
            dismissError = function() {
                var image = $(this).parents('.image');
                image.remove();
            };

        $('.imagegrid .image .delete').live('click', deleteImage);
        $('.imagegrid .image .confirm').live('click', confirmDeleteImage);
        $('.imagegrid .image .cancel').live('click', cancelDeleteImage);
        $('.imagegrid .image .dismiss').live('click', dismissError);
    }

    // SIDEBURN
    // ========
    if ($.fn.sideburn) {
        $('.sideburn .nextitem').click(function(event) {
           $(this).parents('.sideburn').sideburn('next');
           event.preventDefault();
        });
        $('ul.sideburn').sideburn();

        $('#spotlight').each(function() {
            var sideburn = $(this).find('.sideburn'),
                next = $('<span class="nextitem">Next</span>');
            next.click(function() {
                sideburn.sideburn('next');
            });
            $(this).find('.page-header').append(next);
        });
    }
});


