$(window).load(function()
{
    // Hide inactive tabs
    $(".tab_content").hide();
    var at = $("ul.tabs li.active");
    if(at.length) {
        at.show();
        var ac = at.find("a").attr("href");
        $(ac).show();
    } else {
        $("ul.tabs li:first").addClass("active").show(); //Activate first tab
        $(".tab_content:first").show(); //Show first tab content
    }

    /* Chart tabs */
    var tabs = $('#activity-tabs').find('li');
    if(tabs.length) {
        tabs.live('click', function(event) { 
            var current_tab = $(this).find('a').attr('rel');
            $(this).siblings().removeClass('current').end().addClass('current');
            $(this).siblings().find('a').each(function() {
               var hide = $(this).attr('rel');
               $('#'+hide).addClass('hidden');
            });
            $('#'+current_tab).removeClass('hidden');
            return false;
        });
    } else {
        /* Register and Account tabs */
        $("ul.tabs li").click(function() {

            $("ul.tabs li").removeClass("active"); //Remove any "active" class
            $(this).addClass("active"); //Add "active" class to selected tab
            $(".tab_content").hide(); //Hide all tab content

            var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
            $(activeTab).fadeIn(); //Fade in the active ID content
            return false;
        });
    }
   
    // Nav
    var nav = $('#nav li');
    nav.hover(function(event) {
        $(this).addClass('over');
        $(this).siblings().removeClass('over');
        return false;
    }, function(event) {
        $(this).removeClass('over');
        return false;
    });
    
    // Corners
    var box = $('.box');
    if(box.cornerz) {
        box.cornerz({radius: 8});
    }
    var title = $('.box h2.title');
    if(title.cornerz) {
        title.cornerz({radius: 6, corners: "tl tr"});
    }
    var article = $('.article .actions');
    if(article.cornerz) {
        article.cornerz({radius: 6});
    }
    
    // New Topic
    var topic = $('#start-new-topic');
    topic.click(function(event) {
        event.preventDefault();
        $('#new-topic fieldset').toggle('fast');
        return false;
    });
    
    // New Reply
    var reply = $('#post-a-reply');
    reply.click(function(event) {
        event.preventDefault();
        $('#reply fieldset').toggle('fast');
        return false;
    });
    
    // New Comment
    var comment = $('#add-new-comment');
    comment.click(function(event) {
        event.preventDefault();
        $('#comment fieldset').toggle('fast');
        return false;
    });
    
    // Validate forms
    var form = $("#register2-form");
    if(form.validate)
        form.validate();
    var form = $("#comment-form");
    if(form.validate)
        form.validate();
    var form = $("#subscribe-form");
    if(form) {
        if(form.validate)
            form.validate();
        var b = $("a.btn_main");
        if(b) {
            b.click(function(e) {
                $("#subscribe-form").submit();
                return false;
            });
        }
    }


    // Quick Tour
    var qt = $("a#open-quicktour");
    if(qt.fancybox)
        qt.fancybox();

    // Chart 
    var pf = $("#pdf-chart-form");
    if(pf.validate) 
        pf.validate();
    var pdf = $("a#open-pdf-chart");
    if(pdf.fancybox) {
        pdf.fancybox({
            'scrolling': 'no',
            'titleShow': false,
            'hideOnContentClick': false
        });
    }

    // Account
    var bh = $("#firmhdr");
    if(bh) {
        bh.change(function() {
            var src = $(this).val();
            var img = $("#firmhdr-img");
            img.hide();
            img.attr("src", src);
            img.show("slide");
            var f = $("#firmname");
            f.val($("#firmhdr option:selected").text());
        });
    }
    // End of Account

});

function confirmUnsubscribe() {
    if(confirm("Are you sure you want to cancel your subscription?")) {
        var f = $("#unsubscribe-form");
        if(f) {
            f.submit();
        }
    }
}

function viewPDF() {
    var f = $("#pdf-chart-form");
    if(f) {
        $.fancybox.showActivity();
        $.post("printchart.php",
            {
                k: $("#k").val(),
                client: $("#client").val(),
                email: $("#email").val(),
                comments: $("#comments").val(),
                u: $("#u").val()
            },
            function(data) {
                window.location.href = data; 
                $.fancybox.close();
            }
        )
        .error(function() { alert("Failed to generate PDF"); })
        ;
    }
    return false;
}

function emailCheckedSales() {
    var e = $("#email").val();
    if(!e) {
        alert("Please enter a valid email address.");
        return false;
    }
    var n = $("input:checked").length;
    if(n < 1) {
        alert("Please check some sales to email.");
        return false;
    } else {
        var f = $("#form_sales");
        f.append('<input type="hidden" name="email" value="' + e + '" />"');
        f.submit();
    }
}

function checkAll() {
    var c = $("input:checkbox").map(function() {
        this.checked = true;
    });
}

function formatTick(val, axis) {
    return formatNum(val);
}

function formatNum(val) {
    if(val < 100000) {
        return (val).toFixed(0);
    }
    if(val < 1000000) {
        return (val/1000).toFixed(0) + "K";
    } else {
        return (val/1000000).toFixed(2) + "M";
    }
}

function _handle_plothover(event, pos, item, unit) {
    var tip = $("#tip");
    if(item) {
        tip.remove();  
        var lbl = '';
        var y = item.datapoint[1];
        if(item.datapoint[0] < 1000) {
            lbl = unit + formatNum(y);
        } else {
            var dt = new Date(item.datapoint[0]);
            lbl = item.series.label + " (" + dt.toDateString() + ", " + y + ")";
        }
        showPointTip(item.pageX,item.pageY,lbl);
    } else {
        tip.remove();  
    }
}

function handle_plothover(event, pos, item) {
   _handle_plothover(event, pos, item, ''); 
}

function handle_plothover_money(event, pos, item) {
   _handle_plothover(event, pos, item, '$'); 
}

function showPointTip(x, y, contents) {
    var tip = $('<div id="tip">' + contents + '</div>');
    tip.css( {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}

// http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html 
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

