// define some vars
if(window.location.host == 'www.jenox.com') var siteURL = 'http://www.jenox.com/beta/';
else var siteURL = 'http://' + window.location.host + '/Clients/Jenox.com/beta/';

var slideShowOn = true;
var FF3 = false;

$(function() {
    // detect browser
    if($.browser.mozilla && $.browser.version >= 1.9) FF3 = true;
    // activate back to top link
    $('a.top, .footer a.t').click(function(){
        $.scrollTo('div.header',500);
        return false;
    });
    // parse anti-spam emails
    emailParser();
    // autoexpand description field
    if(FF3) $('#description,#featured_description,#reply,#terms').autogrow();
});

function initPortfolios() {
    $('div.portfolios div.client').find('div.caption-wrapper').hide().end().hover(function(){
        $(this).addClass('client-hover').find('div.caption-wrapper').show();
    },function(){
        $(this).removeClass('client-hover').find('div.caption-wrapper').hide();
    });
    $('div.portfolios a.screenshot').lightBox();
}

function initShowcases(type) {
    var $panels = $(type + ' .showcases .client');
    var $container = $(type + ' .showcases');

    // if false, we'll float all the panels left and fix the width 
    // of the container
    var horizontal = true;

    // float the panels left if we're going horizontal
    if (horizontal) {
        $panels.css({
            'float' : 'left',
            'position' : 'relative' // IE fix to ensure overflow is hidden
        });

        // calculate a new width for the container (so it holds all panels)
        $container.css('width', $panels[0].offsetWidth * $panels.length);
    }

    // collect the scroll object, at the same time apply the hidden overflow
    // to remove the default scrollbars that will appear
    var $scroll = $(type + ' .showcases-wrapper').css('overflow', 'hidden');
    
    // handle nav selection
    function selectNav() {
        //console.log('clicked on: ' + $(this).text() + ' ... '+ $(this).attr("href"));
        //console.log('parent: ' + $(this).parents().text());
        
        var slideID = $(this).attr("href");
        
        $('.featured-nav,.slider-nav')
            .find('a')
                .removeClass('selected')
            .end()
            .find('a[href$="' + slideID + '"]')
                .addClass('selected');
    }

    $('.featured-nav a, .slider-nav a').click(function() {
        slideShowOn = false;
        $scroll.trigger('stop');
        selectNav();
    });

    // go find the navigation link that has this target and select the nav
    function trigger(data) {
        var el = $('.featured-nav').find('a[href$="' + data.id + '"]').get(0);
        selectNav.call(el);
    }

    if (window.location.hash) {
        trigger({ id : window.location.hash.substr(1) });
        slideShowOn = false;
    } else {
        //$('.featured-nav a:first').click();
    }
    
    // offset is used to move to *exactly* the right place, since I'm using
    // padding on my example, I need to subtract the amount of padding to
    // the offset.  Try removing this to get a good idea of the effect
    var offset = parseInt((horizontal ? 
        $container.css('paddingTop') : 
        $container.css('paddingLeft')) 
        || 0) * -1;

    var scrollOptions = {
        target: $scroll, // the element that has the overflow

        // can be a selector which will be relative to the target
        items: $panels,
        
        navigation: '.featured-nav a',

        // allow the scroll effect to run both directions
        axis: 'xy',

        onAfter: trigger, // our final callback
        
        offset: offset,

        // duration of the sliding effect
        duration: 500,
        
        interval: 10000,
        force: true,

        // easing - can be used with the easing plugin: 
        // http://gsgd.co.uk/sandbox/jquery/easing/
        easing: 'swing'
    };

    // apply serialScroll to the slider - we chose this plugin because it 
    // supports// the indexed next and previous scroll along with hooking 
    // in to our navigation.
    $(type).serialScroll(scrollOptions);
    
    // now apply localScroll to hook any other arbitrary links to trigger 
    // the effect
    $.localScroll(scrollOptions);

    // finally, if the URL has a hash, move the slider in to position, 
    // setting the duration to 1 because I don't want it to scroll in the
    // very first page load.  We don't always need this, but it ensures
    // the positioning is absolutely spot on when the pages loads.
    scrollOptions.duration = 1;
    $.localScroll.hash(scrollOptions);
    
    $('.slider').hover(
        function(){
            if(slideShowOn) $scroll.trigger('stop');
        },
        function(){
            if(slideShowOn) $scroll.trigger('start');
        }
    );
}

function emailParser() {
    $("span.emailParser").each(function(){
        var email = $(this).find("span.account").text() + '@' + $(this).find("span.provider").text();
        var text = $(this).find("span.text").text();
        $(this).after('<a href="mailto:' + email + '">' + (text != "" ? text : email) + '</a>').remove();
    });
}

function initQuote(mode) {
    switch(mode) {
        case 'view':
            var options = {
                beforeSubmit: function(formArray, jqForm) {
                    $("div.reply_error").remove();
                    if($("#reply").val() == "") {
                        var msg = '<div class="error reply_error">Please enter a reply.</div>';
                        $("form.new_reply").before(msg).fadeIn("fast");
                        setTimeout(function () {
                            $("div.reply_error").fadeOut("slow");
                        }, 1500);
                        return false;
                    } else {
                        $('#reply').attr("disabled", true);
                        $('form.new_reply input.btn').attr("disabled", true).attr("value","Updating Quote...");
                    }
                },
                success: function(data) {
                    var commentsCount = $("div.replies span.count");
                    commentsCount.html(parseInt(commentsCount.text()) + 1);
                    $("div.replies").show().append(data);
                    $("#reply").val("").attr("disabled", false);
                    $('form.new_reply input.btn').attr("disabled", false).attr("value","Add Reply");
                    emailParser();
                }
            };
            $("form.new_reply").prepend('<input type="hidden" name="ajax" value="1"/>').ajaxForm(options);
            
            $("div.view_quote a.editable").click(function(){
                var a_btn = $(this);
                a_btn.hide();
                var quoteReplyID = a_btn.attr("id").replace("qr_","");
                var quoteReplyObj = a_btn.parent().parent().children(".reply");
                var quoteReplyHTML = quoteReplyObj.html();
                quoteReplyObj.html('<form action="'
                    + a_btn.attr("href")
                    + '" method="POST" class="edit_inplace"><input type="hidden" name="mode" value="editReply" /><input type="hidden" name="qrID" value="'
                    + quoteReplyID
                    + '" /><textarea name="reply">'
                    + quoteReplyHTML.replace(/<br>/g,"\n")
                    + '</textarea><input type="submit" value="Update" class="btn update" /> or <input type="reset" value="Cancel" class="btn cancel" /></form>');
                
                if(FF3) $('form.edit_inplace textarea').autogrow();
                
                quoteReplyObj.find(".cancel").click(function(){
                    quoteReplyObj.html(quoteReplyHTML);
                    a_btn.show();
                    
                    return false;
                });
                
                var qr_options = {
                    success: function(reply) {
                        quoteReplyObj.html(reply);
                        a_btn.show();
                    }
                };
                quoteReplyObj.children(".edit_inplace").ajaxForm(qr_options);
                return false;
            });
            break;
        case 'admin':
            initTableForm("quotes");
            break;
    }
}

function initConsultation(mode) {
    switch(mode) {
        case 'view':
            var options = {
                beforeSubmit: function(formArray, jqForm) {
                    $("div.reply_error").remove();
                    if($("#reply").val() == "") {
                        var msg = '<div class="error reply_error">Please enter a reply.</div>';
                        $("form.new_reply").before(msg).fadeIn("fast");
                        setTimeout(function () {
                            $("div.reply_error").fadeOut("slow");
                        }, 1500);
                        return false;
                    } else {
                        $('#reply').attr("disabled", true);
                        $('form.new_reply input.btn').attr("disabled", true).attr("value","Updating Consultation...");
                    }
                },
                success: function(data) {
                    var commentsCount = $("div.replies span.count");
                    commentsCount.html(parseInt(commentsCount.text()) + 1);
                    $("div.replies").show().append(data);
                    $("#reply").val("").attr("disabled", false);
                    $('form.new_reply input.btn').attr("disabled", false).attr("value","Add Reply");
                    emailParser();
                }
            };
            $("form.new_reply").prepend('<input type="hidden" name="ajax" value="1"/>').ajaxForm(options);
            
            $("div.view_consultation a.editable").click(function(){
                var a_btn = $(this);
                a_btn.hide();
                var consultationReplyID = a_btn.attr("id").replace("qr_","");
                var consultationReplyObj = a_btn.parent().parent().children(".reply");
                var consultationReplyHTML = consultationReplyObj.html();
                consultationReplyObj.html('<form action="'
                    + a_btn.attr("href")
                    + '" method="POST" class="edit_inplace"><input type="hidden" name="mode" value="editReply" /><input type="hidden" name="qrID" value="'
                    + consultationReplyID
                    + '" /><textarea name="reply">'
                    + consultationReplyHTML.replace(/<br>/g,"\n")
                    + '</textarea><input type="submit" value="Update" class="btn update" /> or <input type="reset" value="Cancel" class="btn cancel" /></form>');
                    
                if(FF3) $('form.edit_inplace textarea').autogrow();
                
                consultationReplyObj.find(".cancel").click(function(){
                    consultationReplyObj.html(consultationReplyHTML);
                    a_btn.show();
                    return false;
                });
                
                var qr_options = {
                    success: function(reply) {
                        consultationReplyObj.html(reply);
                        a_btn.show();
                    }
                };
                consultationReplyObj.children(".edit_inplace").ajaxForm(qr_options);
                return false;
            });
            break;
        case 'admin':
            initTableForm("consultations");
            break;
    }
}

function initTableForm(fID) {
    $("#" + fID + " input[@name=selectAll]").toggle(function(){
        $("#" + fID).checkCheckboxes();
    },function(){
        $("#" + fID).unCheckCheckboxes();
    });
}