$.fn.removeTableCol = function(col){
    // Make sure col has value
    if(!col){ col = 1; }else{col++;}
    $('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this).remove();
    return this;
};

$.fn.addTableCol = function(){
	this.each(function(){
		var $table = $(this);
		$('tr th:last', $table).before('<th> </th>');
		//$('tbody tr td:last', $table).before('<td> </td>');
		$('tbody tr').each(function(){
			var $row = $(this);
			$('td:last', $row).before('<td> </td>');
		})
	    return this;
	});
};


/*
Add a new table row to the bottom of the table
*/
$.fn.addTableRow = function(){
    this.each(function(){
        var $table = $(this);
        // Number of td's in the last table row
        var n = $('tr:last td', this).length;
        var tds = '<tr>';
        for(var i = 0; i < n; i++){
            tds += '<td> </td>';
        }
        tds += '</tr>';
        if($('tbody', this).length > 0){
            $('tbody', this).append(tds);
        }else {
            $(this).append(tds);
        }
    });
}

/*
Remove the last/bottom table row
*/
/*$.fn.removeTableRow = function(row){
//alert('in da function');
this.each(function(){
    if($('tbody', this).length > 0){
        $('tbody tr:eq('+row+')', this).remove();
    }else {
        $('tr:eq('+row+')', this).remove();
    }
});
}
*/
$.fn.removeTableRow = function(){
//alert('in da function');
	row = $(this).parent().parent();
	$(row).remove();
	/*this.each(function(){
		if($('tbody', this).length > 0){
			$('tbody tr:eq('+row+')', this).remove();
		}else {
			$('tr:eq('+row+')', this).remove();
		}
	});*/
}

function tableInit()
{
	var t  = $('table#manage');
	//set up classes on the various table cells that are to be editable.
	$("th:lt(2)",t).hide();

	$("tr",t).each(function(){
		$('td:lt(2)',this).hide();
		$('td:gt(1):lt(3),td:not(:last):gt(5)',this).each(function(){
			//if($(this).html()!='')
			$(this).addClass('edit');
			//if($(this).text().trim()=='')
		//	{
				//$(this).append('<span class="edit"></span>')
			//}
		});
		$('td:last',this).each(function(){
			//if($(this).text().trim()=='')
			if($.trim($(this).text())=='')
			{
				$(this).append('<a class="removeRow" href="#">Remove product</a>')
			}
		});
		$('td:eq(5)',this).each(function(){
			//if($(this).text().trim()=='')
			//{
				$(this).addClass('select');
			//}
		});
	});
	$('th:not(:last):gt(5)',t).each(function(){
		if($.trim($(this).text())=='')
		{
			$(this).append('<a class="removeColumn" href="#">Remove attribute</a><br/><span class="edit"></span>')
		}
	})
	
	//remove the link that would remove the first product entry as this is the parent product.
	//$('table tbody tr:first td:last').empty();
	
	$('.edit',t).editable('/products/keepAlive');
	$(".select",t).editable("/products/keepAlive",{ 
	    //indicator : '<img src="img/indicator.gif">',
	    data   : "{'Live':'Live','Inactive':'Inactive','Discontinued':'Discontinued'}",
	    type   : "select",
	    submit : "OK"
	  });
	
	
  
	//remove existing click events then re-add
	$('#addRow,.removeRow,#addCol,.removeColumn').unbind('click')
	
	$('#addRow').click(function(){
		$('table#manage').addTableRow();
		tableInit();
		return false;
	});
	$('.removeRow').click(function(){
		//$('table#manage').removeTableRow();
		$(this).removeTableRow();
		//$('table#manage').removeTableRow($('table#manage tbody tr').index($(this).parent()));
		tableInit();
		return false;
	});
	
	$('#addCol').click(function(){
		$('table#manage').addTableCol();
		tableInit();
		return false;
	});
	$('.removeColumn').click(function(){
		//alert($('table#manage thead tr th').index($(this).parent()));
		//alert($.dump(this));
		$('table#manage').removeTableCol($('table#manage thead tr th').index($(this).parent()));
		tableInit();
		return false;
	});
	
	//$("tr,th",t).addClass('edit');
	//for new cells create span so user can edit
}

function saveChanges()
{
	$('#loading').show();
	t = $('table#manage');
	width = $('thead tr th',t).length;
	height = $('tbody tr',t).length;

	var submit = "";
	headers = $('thead tr th',t);

	$('thead tr th:lt(6)', t).each(function(){
		submit = submit + $(this).html() + '#~#';
	});
	$('thead tr th:not(:last):gt(5)', t).each(function(){
		submit = submit + $('span.edit',this).html() + '#~#';
	});
	
	submit = submit + '#$#';
	
	$('tbody tr',t).each(function(){
		
		$('td:lt(2)',this).each(function(){
			submit = submit + $(this).html() + '#~#';
		});
		
		$('td:gt(1):lt(4)',this).each(function(){
			//submit = submit + $('span.edit',this).html() + '#~#';
			submit = submit + $(this).html() + '#~#';
		});
		
		$('td:not(:last):gt(5)',this).each(function(){
			//submit = submit + $('span.att-id',this).html() + ';;' + $('span.edit', this).html() + '#~#';
			submit = submit + $(this).html() + '#~#';
		});
		submit = submit + '#$#';
	});
	
	//alert($.dump(submit));
//	temp = [];
//	for(var y=0;y<width;y++)
//	{
//		if(y==0)
//		{
//			submit[0]= [];
//		}
//		temp[y] =  $(headers[y]).html();
//		//submit[0][y] = $(headers[y]).html();
//	}
//	submit[0] = '[' + temp.toString() +']';
//	for(var x=1;x<=height;x++)
//	{
//		row = $('tbody tr:' + (x-1) + ' td',t);
//		temp = [];
//		for(var y=0;y<width;y++)
//		{
//			if(y==0)
//			{
//				temp = [];
//				//submit[x]= [];
//				
//			}
//			temp[y] =  $(row[y]).html();
////			submit[x][y] = $(row[y]).html();
//		}
//		submit[x] = '[' + temp.toString() +']';
//	}
	//alert($.dump(submit));
	$('#ProductTable').val('' + submit.toString() +'');
	$.post('/admin/update_product', $('#attributeForm').serialize(), function(){
		$('#loading').hide();
	});

	//alert($.dump($('#attributeForm').serialize()));
	
//	t = $('table#manage');
//	var table;
//	table = $('tr',t).each(function(table,i){
//		table[i] = $('th,td',this).html();
//		alert($.dump($('th,td',this).html()));
//		return table;
//	}) 
////	alert($.dump($.table('table#manage').titles()));
//	alert($.dump(table));
	
}

function ajaxFileUpload()
{
	$("#loading")
	.ajaxStart(function(){
		$(this).show();
	})
	.ajaxComplete(function(){
		$(this).hide();
	});

	$.ajaxFileUpload
	(
		{
			url:'/products/uploadtreeimage',
			secureuri:false,
			fileElementId:'TreeImage',
			dataType: 'json',
			success: function (data, status)
			{
				image = $('#TreeLargeImage').val();
				var timestamp = new Date().getTime();
				
				$('#largeimage img').attr("src",'/img/catalog/'+image+'.jpg?'+timestamp);
				$('#mediumimage img').attr("src",'/img/catalog/i'+image+'.jpg?'+timestamp);
				$('#smallimage img').attr("src",'/img/catalog/T'+image+'.jpg?'+timestamp);
				$('#rangeimage img').attr("src",'/img/catalog/Ri'+image+'.jpg?'+timestamp);
				
				//alert(image);
				/*if(typeof(data.error) != 'undefined')
				{
					if(data.error != '')
					{
						alert(data.error);
					}else
					{
						alert(data.msg);
					}
				}*/
			},
			error: function (data, status, e)
			{
				//alert(e);
			}
		}
	)
	
	return false;

}

function minMulCheck(input)
{
	var quantity = $(input).val();
	
	if(minimumQuantity!=0)
	{
		if(minimumQuantity>quantity)
		{
			$(input).val(minimumQuantity);
		}
	}
	if(multipleQuantity!=0)
	{
		if(multipleQuantity>quantity)
		{
			$(input).val(multipleQuantity);
		}
		else if((quantity%multipleQuantity)!=0)
		{
			quantity = quantity - (quantity%multipleQuantity);
			$(input).val(quantity);
		}
	}
}


//**************************************************************************
//Copyright 2007 - 2008 The JSLab Team, Tavs Dokkedahl and Allan Jacobs
//Contact: http://www.jslab.dk/contact.php
//
//This file is part of the JSLab Standard Library (JSL) Program.
//
//JSL is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 3 of the License, or
//any later version.
//
//JSL is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
//***************************************************************************
//File created 2009-01-27 03:05:59

//Return new array with duplicate values removed
Array.prototype.unique =
function() {
 var a = [];
 var l = this.length;
 for(var i=0; i<l; i++) {
   for(var j=i+1; j<l; j++) {
     // If this[i] is found later in the array
     if (this[i] === this[j])
       j = ++i;
   }
   a.push(this[i]);
 }
 return a;
};

