/*
 * jQuery Ajax Grid
 * Uses jQuery v1.2.3
 *
 * Copyright (c) 2008 Constantine Bodunov (bitworks-software.com)
 * Licensed under the GPL (GPL-LICENSE.txt) license.
 *
 * $Date: 2008-09-09 10:42:25 +0600 (Tue, 09 Sep 2008) $
 * $Rev: 1 $
 */

(function($) {

	$.extend({
	    
		grid: new function() {

		    // Default configs
		    this.defaults = {
                jcallback:     '',  // ajax callback
                scallback:     function() {}, // success load callback
                curPage:       1,   // current page
                perPage:       10,  // records per page
                sortPriField:  0,   // sort field number
                sortPriDirect: 0,   // sort direction (0 = asc, 1 = desc)
                sortSecField:  0,   // sort field number
                sortSecDirect: 0,   // sort direction (0 = asc, 1 = desc)
                totalPages:    1,   // private: total pages (return jCallback)
                isAccordion:   0,
                extraParams:   {},
                isAnonymous:   0,
                isReload:      0,
		hidePager:     0
		    };

		    /**
		     * Ctor
		     * Initialize configs and send ajax query to load grid
		     *
		     */
			this.construct = function(settings)
			{
				return this.each(function()
				{
				    this.container = $(this);
				    
				    // Configure grid with settings

					this.config = {};
					config = $.extend(this.config, $.grid.defaults, settings);
					
					// Initialize grid

    				jCallback(this.config, this.container);
				});
			};

		    /**
		     * Send ajax query to load grid
		     *
		     */
			function jCallback(config, container)
			{
			    // Add loading progress

			    if (!config.isReload) {
                    container.html('<img src="' + _APP_URL + '/images/i/grid-load.gif" border="0"/>');
			    }

			    // Generate parameters

			    var arr = {"curPage": config.curPage, "perPage": config.perPage, "sortPriField": config.sortPriField, "sortPriDirect": config.sortPriDirect, "sortSecField": config.sortSecField, "sortSecDirect": config.sortSecDirect};

			    for (s in config.extraParams) {
			        arr[s] = config.extraParams[s];
			    }

			    // Send ajax request

                $.getJSON(config.jcallback, arr, function(json) {

                    if (typeof json != 'object') {
                        return false;
                    }

                    // Marina's authenticate process

                    if (json.auth != 'true' && !config.isAnonymous && false) {

                        $(document.body).append('<div id="body_overlay"></div>');
                        $("#body_overlay").css({'top': 0, 'left': 0, 'width': $(window).width(), 'height': $(document).height(), 'opacity': 0.4});
                        $(document.body).append('<div id="login_form"></div>');
                        $("#login_form").css({'position': 'absolute', 'top': parseInt($(document).height()/2-150), 'left': parseInt($(window).width()/2-180), 'width': '350px', 'height': '170px', 'background-color': 'white', 'z-index': 100, 'padding': '20px', 'opacity': 1.0});
                        $("#login_form").html(json.data);
                        
                        $("#singup_button").click(function() {
                            var params = 'email='+$('#email').val()+'&password='+$('#password').val();
                            if($('#remember').attr('checked')) params += '&remember=1';
                            $.getJSON('/member/login/doAjax?'+params,function(data){
                                if(typeof data == 'object') {
                                    if(data.auth == "false") {
                                        if(data.error) {
                                            $('#error_msgs').html(data.error);
                                            $('#error_msgs').removeClass('hidden');
                                        }
                                    }
                                    else {
                                        /*var params = 'do=login&type=ajax&person_name='+data.person_name+'&password='+$('#password').val();
                                        $.getJSON('/vbulletin/login.php?'+params,function(data){
                                            
                                        });*/
                                        $('#error_msgs').addClass('hidden');
                                        $("#login_form").remove();
                                        $("#body_overlay").remove();
                                        $("#table_overlay").remove();
                                        container.reload(config.extraParams);
                                    }
                                }
                            });
                        });
                    }

                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }
		    
		    		if(config.hidePager == 0) {
                  		container.html('<div style="float: left;"><table id="'+container.attr('id')+'-table" class="tableOuter" cellspacing="0" cellpadding="0" border="0"><thead></thead><tbody></tbody></table><div align="center"><table id="'+container.attr('id')+'-pager" class="grid-pager" cellspacing="0" cellpadding="0" border="0"><tr><td><a id="'+container.attr('id')+'-pager-prevPage" class="grid-prevPage" href=""><img src="/images/i/arrow-left.gif"/></a> <a href="" id="'+container.attr('id')+'-pager-firstPageLink" class="hidden"><span id="'+container.attr('id')+'-pager-firstPage">1</span></a> <span id="'+container.attr('id')+'-pager-firstSpace" class="hidden">...</span> <a href="" id="'+container.attr('id')+'-pager-prevCurPageLink" class="hidden"><span id="'+container.attr('id')+'-pager-prevCurPage">1</span></a> <span id="'+container.attr('id')+'-pager-curPage" class="curPage">1</span> <a href="" id="'+container.attr('id')+'-pager-nextCurPageLink"  class="hidden"><span id="'+container.attr('id')+'-pager-nextCurPage">1</span></a> <span id="'+container.attr('id')+'-pager-lastSpace" class="hidden">...</span> <a href="" id="'+container.attr('id')+'-pager-lastPageLink" class="hidden"><span id="'+container.attr('id')+'-pager-totalPages">1</span></a> <a id="'+container.attr('id')+'-pager-nextPage" class="grid-nextPage" href=""><img src="/images/i/arrow-right.gif"/></a></a></td><td>&nbsp;&nbsp;<select id="'+container.attr('id')+'-pager-perPage" class="pager-perPage"><option value="10" '+(config.perPage == 10 ? 'selected' : '')+'>10</option><option value="30" '+(config.perPage == 30 ? 'selected' : '')+'>30</option><option value="50" '+(config.perPage == 50 ? 'selected' : '')+'>50</option><option value="100" '+(config.perPage == 100 ? 'selected' : '')+'>100</option></select></td></tr></table></div></div><div style="clear: both;">&nbsp;</div>');
		    		}
                  	else {
                  		container.html('<table id="'+container.attr('id')+'-table" class="tableOuter" cellspacing="0" cellpadding="0" border="0"><thead></thead><tbody></tbody></table>');
                  	}

                    var table = $("#"+container.attr('id')+"-table");
                    var tableHeadSection = $("thead", table);
                    var tableBodySection = $("tbody", table);

                    // Bind events to headers

                    tableHeadSection.html(json.head);

                    var tableHeaders = $("thead .grid-sort", table);
				    tableHeaders.each(function(index)
                    {
				        $(this).click(function()
				        {
    				        if (config.sortPriField == index) {
				                config.sortPriDirect = (config.sortPriDirect == 0) ? 1 : 0;
				                if (config.sortPriDirect == 1) {
    				                $(this).attr('class', 'grid-sort grid-sortUp');
				                } else {
    				                $(this).attr('class', 'grid-sort grid-sortDown');
				                }
				            } else {

    			                // set secField simple class
    			                var secHead = $(tableHeaders[config.sortSecField]);
    			                if (config.sortSecDirect == 1) {
    				                secHead.attr('class', 'grid-sort');
    			                } else {
                                    secHead.attr('class', 'grid-sort');
                                }

    				            // set priField as secondary sort class
    				            var priHead = $(tableHeaders[config.sortPriField]);
    				            if (config.sortPriDirect == 1) {
    				                priHead.attr('class', 'grid-sortUp2');
    				            } else {
    				                priHead.attr('class', 'grid-sortDown2');
    				            }
        				            
    				            config.sortSecField  = config.sortPriField;
    				            config.sortSecDirect = config.sortPriDirect;
    				            config.sortPriField  = index;
    				            config.sortPriDirect = 0;
    				            if (config.sortPriDirect == 1) {
    				                $(this).attr('class', 'grid-sort grid-sortUp');
    				            } else {
    				                $(this).attr('class', 'grid-sort grid-sortDown');
    				            }
    				        }
    				        
    				        config.isReload = 1;
                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }

    				        jCallback(config, container);
    				    });
    				});

    				// Bind events to pager

    			    $("#"+container.attr('id')+"-pager-prevPage").click(function()
    			    {
    			        if (config.curPage > 1) {
    			            config.curPage--;
    				        config.isReload = 1;
                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }
    			            jCallback(config, container);
    			        }
    
                        return false;
    			    });
        			    
    			    $("#"+container.attr('id')+"-pager-nextPage").click(function()
    			    {
    			        if (config.curPage < config.totalPages) {
    			            config.curPage++;
    				        config.isReload = 1;
                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }
    			            jCallback(config, container);
    			        }

                        return false;
    			    });
        		        			  
    			    $("#"+container.attr('id')+"-pager-firstPageLink").click(function()
    			    {
    			        if (config.curPage > 1) {
    			            config.curPage = 1;
    				        config.isReload = 1;
                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }
    			            jCallback(config, container);
    			        }
    
                        return false;
    			    });

    			    $("#"+container.attr('id')+"-pager-prevCurPageLink").click(function()
    			    {
    			        config.curPage--;
    				        config.isReload = 1;
                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }
			            jCallback(config, container);
    
                        return false;
    			    });

    			    $("#"+container.attr('id')+"-pager-nextCurPageLink").click(function()
    			    {
    			        config.curPage++;
    				        config.isReload = 1;
                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }
			            jCallback(config, container);
    
                        return false;
    			    });

    			    $("#"+container.attr('id')+"-pager-lastPageLink").click(function()
    			    {
			            if (config.curPage != config.totalPages) {
        			        config.curPage = config.totalPages;
    				        config.isReload = 1;
                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }
    			            jCallback(config, container);
			            }

                        return false;
    			    });

    			    $("#"+container.attr('id')+"-pager-perPage").change(function()
    			    {
    			        config.perPage = this.value;
    				        config.isReload = 1;
                    var table = $("#"+container.attr('id')+"-table");
		    if (table.length && config.isReload) {
			var pos = table.offset();
                        $('#'+container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(), 'opacity': 0.4});
		    }
    			        jCallback(config, container);
                        return false;
    			    });

                    config.totalPages = json.totalPages;

                    if(config.curPage > 1) {
                        $("#"+container.attr('id')+"-pager-prevCurPageLink").removeClass('hidden');
                    }

                    if(config.curPage > 2) {
                        $("#"+container.attr('id')+"-pager-firstPageLink").removeClass('hidden');
                    }

                    if(config.curPage > 3) {
                        $("#"+container.attr('id')+"-pager-firstSpace").removeClass('hidden');
                    }

                    if(config.curPage < 3) {
                        if(!$("#"+container.attr('id')+"-pager-firstPageLink").hasClass('hidden')) {
                            $("#"+container.attr('id')+"-pager-firstPageLink").addClass('hidden');
                        }
                    }

                    if(config.curPage < 4) {
                        if(!$("#"+container.attr('id')+"-pager-firstSpace").hasClass('hidden')) {
                            $("#"+container.attr('id')+"-pager-firstSpace").addClass('hidden');
                        }
                    }

                    if(config.curPage > (config.totalPages - 2)) {
                        if(!$("#"+container.attr('id')+"-pager-lastPageLink").hasClass('hidden')) {
                            $("#"+container.attr('id')+"-pager-lastPageLink").addClass('hidden');
                        }
                    }

                    if(config.curPage > (config.totalPages - 3)) {
                        if(!$("#"+container.attr('id')+"-pager-lastSpace").hasClass('hidden')) {
                            $("#"+container.attr('id')+"-pager-lastSpace").addClass('hidden');
                        }
                    }

                    if(config.curPage < config.totalPages) {
                        $("#"+container.attr('id')+"-pager-nextCurPageLink").removeClass('hidden');
                    }

                    if(config.curPage < config.totalPages-1) {
                        $("#"+container.attr('id')+"-pager-lastPageLink").removeClass('hidden');
                    }

                    if(config.curPage < config.totalPages-2) {
                        $("#"+container.attr('id')+"-pager-lastSpace").removeClass('hidden');
                    }

                    if(config.curPage == config.totalPages) {
                        if(!$("#"+container.attr('id')+"-pager-nextCurPageLink").hasClass('hidden')) {
                            $("#"+container.attr('id')+"-pager-nextCurPageLink").addClass('hidden');
                        }
                    }

                    $("#"+container.attr('id')+"-pager-prevCurPage").html(config.curPage-1);
                    $("#"+container.attr('id')+"-pager-curPage").html(config.curPage);
                    $("#"+container.attr('id')+"-pager-nextCurPage").html(config.curPage+1);
                    $("#"+container.attr('id')+"-pager-totalPages").html(config.totalPages);

                    // Generate table body

    			    var tableBodySection = $("tbody", table);
    				tableBodySection.html(json.data);

    				// Execute external scallback when data loaded

                    config.scallback();

                    if (config.isReload) {
                        $('#table_overlay').remove();
                    }

                    // Attach accordion to grid

                    if (table.attr('class') != 'tableOuter ui-accordion' && config.isAccordion) {
                        table.accordion({
                        	autoheight: false,
                        	event: 'click',
                        	header: 'tr[class="data tableBodyRow"]',
                        	animated: ''
                        })
                    }

		            // Set sort arrow to header

		            var priHead = $(tableHeaders[config.sortPriField]);
		            if (config.sortPriDirect == 1) {
		                priHead.attr('class', 'grid-sort grid-sortUp');
		            } else {
		                priHead.attr('class', 'grid-sort grid-sortDown');
		            }
                });
			};
			
			this.reload = function(extraParams)
			{
			    this[0].config.extraParams = extraParams;
			    this[0].config.isReload = 1;
			    
                var table = $("#"+this[0].container.attr('id')+"-table");
                if (table.length && this[0].config.isReload) {
                    var pos = table.offset();
                    if(!document.getElementById("table_overlay")) {
    			$('#'+this[0].container.attr('id')+'').prepend('<div id="table_overlay"></div>');
                	$("#table_overlay").css({'top': pos.top, 'left': pos.left, 'width': table.width(), 'height': table.height(),'opacity' : '0.5','background-color': '#fff'});
            	    }
		}
			    
			    jCallback(this[0].config, this[0].container);
			    delete this[0].config.extraParams['hideParams'];
			}
		}
	});
	
	$.fn.extend({
        grid:   $.grid.construct,
        reload: $.grid.reload
	});

})(jQuery);