$(document).ready(function(){
	$("a[rel='addproduct']").colorbox({width:"60%", height:"60%", iframe:true});
	$("a[rel='dealerinfo']").colorbox({width:"640px", height:"580px", iframe:true});
	//$("a[rel='galleryshow']").colorbox({slideshow:true, transition:"fade", slideshowAuto:false});

	$('a[id$="lnkForgotPass"]').click(function() { 
	    $('div[id$="plForgotPassContainer"]').prev().hide();
	    $('div[id$="plForgotPassContainer"]').slideToggle(200);
	    return false;
	});
	$('a[id$="lnkRequestAccess"]').click(function() { $('div#requestaccess').slideToggle(200); return false; });
	/*$('.galleryitem img').animate({width: 100}, 0);
	$('.galleryitem').mouseover(function(){
			gridimage = $(this).find('img'); gridimage.stop().animate({width: 180}, 'fast');
		}).mouseout(function(){
			gridimage.stop().animate({width: 100}, 'fast');
	});				
	$('.gallery').mouseover(function(){ $('.clickhere').show(); }).mouseout(function() { $('.clickhere').hide(); });*/

    $('.GridTable tr').find('td:first').each(function() {
        if ($(this).find('a').length > 0)
            $(this).hover(function() { $(this).parent().toggleClass('selectable-row'); }, function() { $(this).parent().toggleClass('selectable-row'); });
    });
    $('.GridTable tr th:last').find('input[type="checkbox"]').each(function() {
        $(this).click(function() {
            var mode = this.checked;
            $('.GridTable tr').find('td:last input[type="checkbox"]').each(function() { this.checked = mode; });
        });
    });
    
    var _m = "ma" + "i" + "lto:", _e = [["mindy","dale"]], _d = "paulsenmarketing";
    _m = _m+_e[0][0]+'.'+_e[0][1]+'@'+_d+'.com'/*+_e[1][0]+'.'+_e[1][1]+'@'+_d+'.com';*/
    _m += '&subject=Online Dealer Toolkit Help';
    // $('li a.help').attr('href', _m);
    
    //setTimeout("$('.confirmation-summary').animate({opacity:0}).slideUp(500);",6500);
});

var RBO = {
    Controls: {
        Colorbox: {
            /*_attach: function(id,event,handler) {
            $('#'+id).bind(event, handler);
            },*/
            Close: function(refresh) {
                $.fn.colorbox.close();
                if (refresh)
                    top.window.location = top.window.location;
            }
        },
        Handler: function(o) {
            if (o.error && !o.redirect)
                $('div.validation-summary').html('The following error has occured:<ul><li>' + o.error + '</li></ul>').show();
            else if (!o.error)
                $('div.validation-summary').html('').hide();
            if (o.redirect)
                top.window.location = o.redirect;
        }
    },
    
    Export: {
        File: function(context, path, file, type) {
            var src = context + '/repository/_file-download.aspx?type=' + type + '&path=' + path.replace('\\\\', '\\') + '&file=' + file;
            if ('preview' == type)
                window.open(src);
            else
                $('#ifrmExport').attr('src', src);
        }
    },
    
    ChartGenerator: {
        Chart: {
            Comments: {
                _is_open: false,
                Init: function(o) {
                    if (this._is_open)
                        this.Cancel();
                    var data = $(o).siblings('input[id$="hdnFullComment"]').val();
                    var html = '<div class="inline-textedit"><textarea>' + data + '</textarea><span>';
                    html += '<a id="cc" href="javascript:;">cancel</a> &nbsp; <a id="cs" href="javascript:;">save</a></span></div>';
                    $(o).parent().prepend(html);
                    $(o).parent().find('a#cc, a#cs').each(function() {
                        if ($(this).attr('id') == 'cc') $(this).click(function() { RBO.ChartGenerator.Chart.Comments.Cancel($(this)); });
                        if ($(this).attr('id') == 'cs') $(this).click(function() { RBO.ChartGenerator.Chart.Comments.Save($(this)); });
                    });

                    $(o).parents('tr').addClass('selectable-row');
                    this._is_open = true;
                },
                Cancel: function(o) {
                    $('div.inline-textedit').each(function() { $(this).parents('tr').removeClass('selectable-row').end().remove(); });
                    this._is_open = false;
                },
                Save: function(o) {
                    var chartProductId = $(o).parents('tr').find('input[id$="hdnRecordId"]').val();
                    var data = $(o).parents('div').find('textarea').val();
                    ChartGenerator.SaveItemComment(chartProductId, data, RBO.ChartGenerator.Chart.Comments._save_oncomplete, _MSAjax_OnError, _MSAjax_OnTimeOut);
                    var tmp = $.trim(data); if (tmp.length > 41) tmp = $.trim(tmp.substring(0, 41)) + '...';
                    $(o).parents('div').siblings('span[id$="lblColumn4"]').html(tmp);
                    $(o).parents('td').find('input[id$="hdnFullComment"]').val(data);
                    this.Cancel();
                },
                _save_oncomplete: function(data) {
                    var o = eval('(' + data + ')');
                    if (o.success) {
                        $('span[id$="lblLastUpdated"]').html('Last Updated: ' + o.updated);
                    }
                    else
                        RBO.Controls.Handler(o);
                }
            },

            Sort: function(type, data) {
                ChartGenerator.SortItems(type, data.toString(), RBO.ChartGenerator.Chart._sort_oncomplete, _MSAjax_OnError, _MSAjax_OnTimeOut);
            },
            _sort_oncomplete: function(data) {
                var o = eval('(' + data + ')');
                if (o.success) {
                    if (o.updated.length > 0)
                        $('span[id$="lblLastUpdated"]').html('Last Updated: ' + o.updated);
                }
                else
                    RBO.Controls.Handler(o);
            }
        },
        Products: {
            Utility: {
                _path: [], _updated_needed: false,
                toggle: function(which) {
                    if (which == 'nutrient') {
                        if ($('#nutrient-list').length > 0) {
                            $('#nutrient-list').remove(); $('#item-list, #header-column').show();
                            $('h3 a:first').click(function() { RBO.ChartGenerator.Products.Utility.Init(); });
                        }
                    }
                },

                Init: function() {
                    $('.loading').toggle();
                    ChartGenerator.ProductUtilityInit(RBO.ChartGenerator.Products.Utility._productutilityinit_oncomplete, _MSAjax_OnError, _MSAjax_OnTimeOut);
                },
                _productutilityinit_oncomplete: function(data) {
                    var o = eval('(' + data + ')'); var html = ''
                    if (o.success) {
                        $('#nutrient-list, #item-list, #header-column').remove();
                        $('#product-list').empty().show(); $('h3').html('Species');

                        for (var i = 0; i < o.species.length; i++) {
                            var alt = i % 2 == 0 ? 'background:#ececec;' : '';
                            var title = o.species[i].count > 0 ? '<span>' + o.species[i].title + '</span>' : '<em>' + o.species[i].title + '</em>';
                            html += '<div id="specie_' + o.species[i].id + '" style="' + alt + '">' + title;

                            if (o.species[i].applications.length > 0) {
                                for (var a = 0; a < o.species[i].applications.length; a++) {
                                    var application = o.species[i].applications[a];
                                    title = application.count > 0 ? '<span>' + application.title + '</span>' : '<em>' + application.title + '</em>';
                                    html += '<div id="application_' + application.id + '" style="display:none">' + title;
                                    if (application.supplements.length > 0) {
                                        for (var s = 0; s < application.supplements.length; s++) {
                                            var supplement = application.supplements[s];
                                            title = supplement.count > 0 ? '<span>' + supplement.title + '</span>' : '<em>' + supplement.title + '</em>';
                                            html += '<div id="supplement_' + supplement.id + '" style="display:none">' + title + '</div>';
                                        }
                                    }
                                    html += '</div>';
                                }
                            }
                            else if (o.species[i].supplements.length > 0) {
                                for (var s = 0; s < o.species[i].supplements.length; s++) {
                                    var supplement = o.species[i].supplements[s];
                                    title = supplement.count > 0 ? '<span>' + supplement.title + '</span>' : '<em>' + supplement.title + '</em>';
                                    html += '<div id="supplement_' + supplement.id + '" style="display:none">' + title + '</div>';
                                }
                            }
                            html += '</div>';
                        }
                        $('#product-list').append(html);
                        $('#product-list div span').each(function(index) {
                            $(this).click(function() {
                                $(this).toggleClass('selected');
                                if ($(this).siblings().length > 1)
                                    $(this).siblings().slideToggle();
                                else
                                    RBO.ChartGenerator.Products.Utility.Load($(this));
                            });
                        });
                    }
                    else
                        RBO.Controls.Handler(o);
                    $('.loading').toggle();
                },
                Load: function(o) {
                    var parents = $(o).parents('div');
                    var json = new Array();
                    $.each(parents, function(index) {
                        var id = $(this).attr('id');
                        if ('product-list' == id)
                            return true;
                        else {
                            id = id.split('_');
                            if (id[1])
                                json.push(id[1] + ':' + id[0]);
                        }
                    });
                    $('.loading').toggle();
                    ChartGenerator.ProductUtilityLoad(json.toString(), RBO.ChartGenerator.Products.Utility._productutilityload_oncomplete, _MSAjax_OnError, _MSAjax_OnTimeOut);
                },
                _productutilityload_oncomplete: function(data) {
                    var o = eval('(' + data + ')'); var html = '';
                    if (o.success) {
                        $('h3').empty().append(o.path);
                        if (o.product.length > 0) {
                            $('#product-list').empty().hide();
                            for (var i = 0; i < o.product.length; i++) {
                                var alt = i % 2 == 0 ? 'background:#ececec;' : '';
                                html += '<tr id="divProd' + i + '" style="' + alt + '" class="item">';
                                html += '<td width="80"><input type="checkbox" id="chkProd' + i + '" value="' + o.product[i].id + '" /><label for="chkProd' + i + '">Add</label></td>';
                                html += '<td width="75">' + o.product[i].number + '</td>';
                                html += '<td width="375"><strong>' + o.product[i].name + '</strong></td>';
                                html += '<td align="right"><a href="javascript:" onclick="RBO.ChartGenerator.Products.Utility.ListNutrients(' + o.product[i].id + ',this,\'add\');">View Nutrition Details</a></td>';
                                html += '</tr>';
                            }
                            var html_col = '<table id="header-column" border="0" width="100%" cellspacing="0" cellpadding="0" style="padding:4px 0;border-top:1px solid #000">';
                            html_col += '<tr><td width="80"><input id="sall" name="sall" onclick="selectall(this);" type="checkbox"/><label for="sall">Select All</label></td><td width="75"><strong>Item Code</strong></td><td><strong>Item Name</strong></td></tr>';
                            html_col += '</table>';
                            html = '<table border="0" width="685" cellpadding="0" cellspacing="0">' + html + '</table>';
                            $('#product-list').before(html_col);
                            $('#product-list').after('<div id="item-list">' + html + '</div>');
                        }
                        $('h3 a:first').click(function() { RBO.ChartGenerator.Products.Utility.Init(); });
                    }
                    else
                        RBO.Controls.Handler(o);
                    $('.loading').toggle();
                },
                ListNutrients: function(id, o, util) {
                    var load = !($(o).parent().next().attr('id') == 'nutrient-list');
                    var div = $('#nutrient-list');
                    if ($(div).length > 0) {
                        $(div).prev().find('a').html('View Nutrition Details');
                        $(div).slideUp('fast').remove();
                    }
                    if (load) {
                        var chk = $(o).parents('tr').find('input[type="checkbox"]').is(':checked') ? 'true' : 'false';
                        $('.loading').toggle();
                        ChartGenerator.ProductUtilityNutrientLoad(id, $(o).parent().attr('id'), util, chk, RBO.ChartGenerator.Products.Utility._productutilitylistnutrients_oncomplete, _MSAjax_OnError, _MSAjax_OnTimeOut);
                    }
                },
                _productutilitylistnutrients_oncomplete: function(data) {
                    var o = eval('(' + data + ')'); var html = '', html_col_1 = '', html_col_2 = '';
                    if (o.success) {
                        $('#item-list, #header-column').hide();

                        html += '<table border="0" width="100%" cellpadding="0" cellspacing="0">';
                        html += '<tr id="divProd" style="background:#ececec;" class="item">';
                        html += '<td width="80"><input type="checkbox" id="chkProd" value="' + o.product.Id + '" ' + (o.checked == 'true' ? 'checked' : '') + ' /><label for="chkProd">Add</label></td>';
                        html += '<td width="75">' + o.product.Number + '</td>';
                        html += '<td width="350"><strong>' + o.product.Name + '</strong></td>';
                        html += '<td align="right"><a href="javascript:;" onclick="RBO.ChartGenerator.Products.Utility.toggle(\'nutrient\');">Hide Nutrition Details</a></td></tr></table>';

                        var colcount = Math.round(o.nutrients.length / 2);
                        for (var i = 0; i < colcount; i++)
                            html_col_1 += '<tr><td width="175">' + o.nutrients[i].title + '</td><td width="75" align="right">' + o.nutrients[i].data + '</td></tr>';
                        html_col_1 = '<table border="0" style="float:left;margin-left:25px">' + html_col_1 + '</table>';
                        for (var i = colcount; i < o.nutrients.length; i++) {
                            if (o.nutrients[i])
                                html_col_2 += '<tr><td width="175" style="float:left;margin-left:25px">' + o.nutrients[i].title + '</td><td width="75" align="right">' + o.nutrients[i].data + '</td></tr>';
                        }
                        html_col_2 = '<table border="0">' + html_col_2 + '</table>';

                        if (o.utility == 'nutrient')
                            html = '<div id="nutrient-list"><br /><br />' + html_col_1 + html_col_2 + '</div>';
                        else
                            html = '<div id="nutrient-list">' + html + '<br /><strong>Nutrient Guarantees</strong><br /><br />' + html_col_1 + html_col_2 + '</div>'

                        $('#product-list').hide();
                        $('#product-list').after(html);
                        $('h3 a:first').unbind('click').click(function() { RBO.ChartGenerator.Products.Utility.toggle('nutrient'); });
                    }
                    else
                        RBO.Controls.Handler(o);
                    $('.loading').toggle();
                },
                Add: function() {
                    var json = new Array();
                    $('#item-list input[type="checkbox"], #nutrient-list input[type="checkbox"]').each(function() {
                        if ($(this).is(':checked'))
                            json.push($(this).val());
                    });
                    if (json.length > 0) {
                        $('#product-list input[type="checkbox"]').attr('disabled', 'disabled');
                        var chartId = $('input[id$="hdnChartId"]').val();
                        $('.loading').toggle();
                        ChartGenerator.ProductUtilityAdd(chartId, json.toString(), RBO.ChartGenerator.Products.Utility._productutilityadd_oncomplete, _MSAjax_OnError, _MSAjax_OnTimeOut);
                    }
                },
                _productutilityadd_oncomplete: function(data) {
                    var o = eval('(' + data + ')'); var html = ''
                    if (o.success) {
                        $('#product-list input[type="checkbox"]').removeAttr('disabled');
                        var message = "<strong>" + o.count + "</strong> product(s) have been added to your chart.";
                        if (o.exist > 0)
                            message += "<br />Some product(s) you selected already exist in your chart and were not re-added.";
                        if (o.count > 0)
                            RBO.ChartGenerator.Products.Utility._updated_needed = true;
                        top.RBO.Controls.Colorbox.Close(RBO.ChartGenerator.Products.Utility._updated_needed);
                    }
                    else
                        RBO.Controls.Handler(o);
                    $('.loading').toggle();
                }
            }
        }
    }
}

function _MSAjax_OnComplete(arg)
{
    //alert(arg);
    return true;
}
function _MSAjax_OnError(arg)
{
    alert("error has occured: " + arg.get_message());
}
function _MSAjax_OnTimeOut(arg)
{
   alert("timeout has occured");
}
