var My = {}     
My.List = {
        Filter : function (inputSelector, listSelector) {

                // Sanity check 
                var inp, rgx = new RegExp(), titles = $(listSelector), keys;
                if (titles.length === 0) {
                        return false;
                }

                // The list with keys to skip (esc, arrows, return, etc)
                // 8 is backspace, you might want to remove that for better usability
                keys = [ 13, 27, 37, 38, 39, 40 ];

                // binding keyup to the unordered list
                $(inputSelector).bind('keyup', function (e) {
                        if (jQuery.inArray(e.keyCode, keys) >= 0) {
                                return false;
                        }

                        // Building the regex from our user input, 'inp' should be escaped
                        inp = $(this).attr('value');
                        rgx.compile(inp, 'im');
                        titles.each(function () {
                                if (rgx.source !== '' && !rgx.test($(this).html())) {
                                        $(this).parent('li').hide();
                                } else {
                                        $(this).parent('li').show();   
                                }
                        });
                });
        }
};


$(document).ready(function(){

	My.List.Filter('input#product_filter', '#availableproducts>li>ul>li>a');


	$("#partnumber").autocomplete({  
		source: "../../search/sparepart",
		minLength: 2
	});

	$("#partsearch").autocomplete({  
		source: "../../manage/spareparts/search_spares",
		minLength: 3
	});
	
/*
	$("#partsearch").change(function(){
		$(this);
	});
*/

	zebraStripe();
	deleteSpare();
	deleteFinish();
//	deleteLine();
	imageUpload();
	lineUpload();
	deleteAssociated();
	buttonStyle();
	fancyLink();
	formatNum();
	
//TABBED BROWSING HISTORY

  var tabs = $('.tabs'),
    
    // This selector will be reused when selecting actual tab widget A elements.
    tab_a_selector = 'ul.ui-tabs-nav a';
  
  // Enable tabs on all tab widgets. The `event` property must be overridden so
  // that the tabs aren't changed on click, and any custom event name can be
  // specified. Note that if you define a callback for the 'select' event, it
  // will be executed for the selected tab whenever the hash changes.
  tabs.tabs({ event: 'change' });
  
  // Define our own click handler for the tabs, overriding the default.
  tabs.find( tab_a_selector ).click(function(){
    var state = {},
      
      // Get the id of this tab widget.
      id = $(this).closest( '.tabs' ).attr( 'id' ),
      
      // Get the index of this tab.
      idx = $(this).parent().prevAll().length;
    
    // Set the state!
    state[ id ] = idx;
    $.bbq.pushState( state );
  });
  
  // Bind an event to window.onhashchange that, when the history state changes,
  // iterates over all tab widgets, changing the current tab as necessary.
  $(window).bind( 'hashchange', function(e) {
    
    // Iterate over all tab widgets.
    tabs.each(function(){
      
      // Get the index for this tab widget from the hash, based on the
      // appropriate id property. In jQuery 1.4, you should use e.getState()
      // instead of $.bbq.getState(). The second, 'true' argument coerces the
      // string value to a number.
      var idx = $.bbq.getState( this.id, true ) || 0;
      
      // Select the appropriate tab for this tab widget by triggering the custom
      // event specified in the .tabs() init above (you could keep track of what
      // tab each widget is on using .data, and only select a tab if it has
      // changed).
      $(this).find( tab_a_selector ).eq( idx ).triggerHandler( 'change' );
    });
  })
  
  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).trigger( 'hashchange' );
  

	
// ADD FINISH	
	$('#addfinish').submit(function(){
		//When submitted do an ajaxSubmit
		$(this).ajaxSubmit({
			dataType: 'json',
			success: function(data, responseCode) {
				var id = data.prod_id;
				var row = '<table><thead><tr class="odd"><th style="width: 100px"><strong>Finish Type</strong></th><th style="width: 100px"><strong>US Price</strong></th><th style="width: 100px"><strong>Canada Price</strong></th><th style="width: 100px"><strong>Image</strong></th><th style="width: 100px"></th></tr></thead><tr><td class="finishname">'+data.finishname+'</td><td class="usaprice"><input type="text" size="7" class="price field" value="'+data.usaprice+'" name="us_price" id="us_price"></td><td class="canadaprice"><input type="text" size="7" class="price field" value="'+data.canadaprice+'" name="can_price" id="can_price"></td><td  class="finishimage" id="'+data.prodno+'"><div class="'+data.prodno+data.image+'" <a title="'+data.prodno+data.image+'" class="fancyLink" href="../../media/products/default/full/IKONP'+data.image+'.jpg"><img class="'+data.prodno+data.image+'" alt="Default Finish" src="../..//media/products/default/thumbnails/IKONP'+data.image+'.jpg"></a><br><h3 class="'+data.prodno+data.image+'">Select File</h3></div></td><td><button name="savefinish" id="savefinish" type="submit" class="btn_no_text ui-state-default ui-corner-all tooltip save" title="Save Changes" style="float: left; padding: 2px;"><span class="ui-icon ui-icon-circle-check"></span></button><a class="btn_no_text btn ui-state-default ui-corner-all tooltip delete" rel="'+data.finish_id+'" title="Remove Finish" href="../../products/deletefinish/'+data.finish_id+'"><span class="ui-icon ui-icon-circle-close"></span></a></td></tr><tr class="odd"><td colspan="5"> <label for="canadian">Exclude Canada</label><input type="checkbox" value="y" name="canadian" id="canadian"><label for="disco">Discontinued</label><input type="checkbox" value="y" name="discontinued" id="discontinued"><label for="webonly">Web Only</label><input type="checkbox" value="1" name="webonly" id="webonly"></td></tr></table>';
				$(row).appendTo('#availablefinishes').hide().fadeIn();
				$("#finish option[value='"+data.id+"']").remove();
				$("#defaultfin").append('<option value="'+data.id+'">'+data.finishname+'</option>')
				buttonStyle();
				fancyLink();
				zebraStripe();
				imageUpload();
			}

		});

		return false;
	});
	



//ADD ASSOCIATED PRODUCTS 
	var $associated = $('#associatedproducts'), $available = $('#availableproducts');
	$('ul li',$available).draggable({
		cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
		revert: 'invalid', // when not dropped, the item will revert back to its initial position
		helper: 'clone',
		cursor: 'move'
	});
	// let the trash be droppable, accepting the gallery items
	$associated.droppable({
		accept: '#availableproducts > li > ul > li',
		//activeClass: 'ui-state-highlight',
		drop: function(ev, ui) {
			addAssociate(ui.draggable);
		}
	});
	function addAssociate($item) {
		var currentProd = $('a', $item).attr("class");
		var newProd = $('a', $item).attr("title");
		$item.fadeOut(function() {
			var $list = $('ul',$available).length ? $('ul',$available) : $('<ul class="gallery ui-helper-reset"/>').appendTo($available);
		});
		$(this).ajaxSubmit({
			dataType: 'json',
			url: '../addassociated',
			data: {id: currentProd, associated: newProd},
			success: function(data, responseCode) {
				var row = '<tr><td><a class="tooltip" title="View Product" href="../view/'+data.prodno.replace(" ", "+")+'">'+data.prodno+'</a></td><td><div class="grid_10">'+data.description+'</td><td><a class="btn_no_text btn ui-state-default ui-corner-all tooltip delete" title="Remove Associated Product" rel="'+data.id+'" href="../deleteassociated/'+data.id+'"><span class="ui-icon ui-icon-circle-close"></span></a></td></tr>';
				$('#associatedproducts tr.assocempty').hide(); //take away the deleted record from the table with a nice fade out
				$(row).appendTo('#associatedproducts').hide().fadeIn();
				buttonStyle();
				zebraStripe();
			}
		});
	}





// ADD SPARE PART	
	$('#addpart').submit(function(){
		//When submitted do an ajaxSubmit
		$(this).ajaxSubmit({
			dataType: 'json',
			success: function(data, responseCode) {
				var selected = new Array();
				selected['n'] = 'No';
				selected['y'] = 'Yes';
				var dropdown = "";

				for (var i in selected)
				{
				var select = (data.optional == i) ? ' selected="selected"' : '';
				dropdown += '<option value="'+i+'"'+select+'>'+selected[i]+'</option>';
				}
				
				var row  = '<tr><td><input type="text" size="4" name="pos_no" class="field" value="'+data.pos_no+'" /></td><td><p>'+data.description+'</p></td><td><p><a class="tooltip" title="Edit Spare Part" href="../../manage/spareparts/edit/'+data.sp_prod_no.replace(" ", "+")+'">'+data.sp_prod_no+'</a></p></td><td><input type="text" size="2" name="pieces" class="field" value="'+data.pieces+'" /></td><td><select id="optional" class="field">'+dropdown+'</select></td><td><button type="submit" class="btn_no_text ui-state-default ui-corner-all tooltip save" title="Save Changes" style="float: left; padding: 2px;"><span class="ui-icon ui-icon-circle-check"></span></button><a class="btn_no_text btn ui-state-default ui-corner-all tooltip delete" rel="'+data.id+'" title="Remove Sparepart" href="../../products/deletespare/'+data.id+'"><span class="ui-icon ui-icon-circle-close"></span></a></td></tr>';
				$(row).appendTo('#partslist').hide().fadeIn();
				buttonStyle();
				sortSpares();
			}
		});
		return false;
	});
	
	


		//<td><?=form::dropdown('optional', $optional, $result['optional'], 'class="field"');?></td>
// DELETE ASSOCIATED PRODUCT	
function deleteAssociated(){
	$('#associatedproducts').delegate("a.delete", "click", function()
	{

	
		var answer = confirm('Remove associated product');
		if(answer==true)
		{
		    var id = $(this).attr("rel");
		    $.ajax( 
			{
				url: "../deleteassociated/"+id,
				type:"POST",
				dataType: "json",
				success: function(result)
				{
					   $('#associatedproducts tr:has(td a[rel ="'+id+'"])').fadeOut('slow'); //take away the deleted record from the table with a nice fade out
					   
				}
			});
		}
  		return false
	});
}


// DELETE LINE	
/*
function deleteLine(){
	$('.remove_line').bind("click", function()
	{

	
		var answer = confirm('Remove line');
		if(answer==true)
		{
		    var id = $(this).attr("rel");
		    $(this).ajaxSubmit( 
			{
				url: "../remove_line/"+id,
				type:"POST",
				dataType: "json",
				success: function(data, responseCode)
				{
					   $(this).fadeOut('slow');
	//				   $(this).prev("select").fadeOut('slow');
				}
			});
		}
  		return false
	});
}
*/


// DELETE ASSOCIATED FINISH	
function deleteFinish(){
	$('#finishes').delegate("a.delete", "click", function()
	{

	
		var answer = confirm('Remove finish');
		if(answer==true)
		{
		    var id = $(this).attr("rel");
		    $(this).ajaxSubmit( 
			{
				url: "../deletefinish/"+id,
				type:"POST",
				dataType: "json",
				success: function(data, responseCode)
				{
					   $('#finishes table:has(td a[rel ="'+id+'"])').fadeOut('slow');
					   $("#defaultfin option[value='"+data.id+"']").remove();
					   $("#finish").append('<option value="'+data.id+'">'+data.finishname+'</option>')
				}
			});
		}
  		return false
	});
}

// DELETE SPARE PART
function deleteSpare(){
	$('#partslist').delegate("a.delete", "click", function()
	{
		var answer = confirm('Delete spare part');
		if(answer==true)
		{
		    var id = $(this).attr("rel");
		    $.ajax( 
			{
				url: "../deletespare/"+id,
				type:"POST",
				dataType: "json",
				success: function(result)
				{
					   $('#partslist tr:has(td a[rel ="'+id+'"])').fadeOut('slow'); //take away the deleted record from the table with a nice fade out
				}
			});
		}
  		return false
	});
}

function buttonStyle()
{
	$("button, input:submit, a.submit").button();
	$(function() {
		$('.tooltip').tooltip({
			track: true,
			delay: 0,
			showURL: false,
			showBody: " - ",
			fade: 250
			});
		});
}

function fancyLink()
{
	$('a.fancyLink').colorbox({height:"75%"});
}

function sortSpares()
{
	var table = $('#partslist');
	var items = table.children('.position').get();
	items.sort(function(a, b) {
	   var compA = $(a).text().toUpperCase();
	   var compB = $(b).text().toUpperCase();
	   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
	})
	$.each(items, function(idx, itm) { table.append(itm); });
}



function imageUpload()
{	
	$('.prodedit td.finishimage').each(function()
	{
		 var id = $(this).attr("id");
		 var img = $('a', this).attr("title");
		 var fin_id = $('a', this).attr("rel");
		 var code = img;
	      var thumbnail = $('img.'+img);
	      var button = $('h3.'+img), interval;
	      new AjaxUpload(button, {
	      action: '../../forms/formimage/preview',
	      name: 'file',
	      data: {
	              prodno: id,
	              code: img,
	              fin_id: fin_id
	              },
	
	      onSubmit: function(file, extension) {
	          $('div.'+img).addClass('loading');
	      },
	      onComplete: function(file, response) {
	          $('div.'+img).removeClass('loading');
	          thumbnail.unbind();
	          thumbnail.attr('src', '../../media/products/detail/thumbnails/50/'+img+'.jpg');
	          thumbnail.attr('href', '../../media/products/detail/full/'+img+'.jpg');

	      }
	
	      });

	});
}

function lineUpload()
{	
	$('.lineimage').each(function()
	{
		 var id_temp = $(this).attr("id");
		 var id = id_temp.replace("line_", "");
	      var thumbnail = $('img.'+id);
	      var button = $('h3.'+id), interval;
	      new AjaxUpload(button, {
	      action: '../../../forms/formimage/lines',
	      name: 'file',
	      data: {
	              id: id
	              },
	
	      onSubmit: function(file, extension) {
	          $('div.'+id).addClass('loading');
	      },
	      onComplete: function(file, response) {
	          $('div.'+id).removeClass('loading');
	          thumbnail.unbind();
	          thumbnail.attr('src', '../../../media/lines/'+id+'.jpg');
	          thumbnail.attr('href', '../../../media/lines/'+id+'.jpg');

	      }
	
	      });

	});
}

function zebraStripe()
{
	$('tr:even').addClass('even');
	$('tr:odd').addClass('odd');
	$('#availableproducts li ul li:odd').addClass('odd');
}


function formatNum()
{

// Check to make sure number needs to be formatted
$('#product_number, #sp_prod_no input, #availablefilter input').bind('keyup click blur focus change paste', function()
	{

			var num;
			num = $(this).val();
			
			var new_num;
			var new_num = $(this).val();
	
			if ((new_num.length >= 3) && (new_num.length <= 6) && (new_num.match(/\d+$/)) && (new_num.charAt(2) !== " "))
				{  
				var first = new_num.substring(0,2);
				var last = new_num.substring(2, new_num.length);
				new_num = first + " " + last;
				$(this).val(new_num);
			        }
			        
			if ((new_num.length >= 7) && (new_num.match(/\d+$/)) )
				{  

				new_num = new_num.replace(" ", "");
				$(this).val(new_num);
			        }
			        
});
}

function finish_list_update(id)
{

	$.getJSON("../../forms/formimage/finish_list_update",{id: id, ajax: 'true'}, function(j){
		var options = '';
		for (var i = 0; i < j.length; i++) {
			options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
		}
	
		$("select#availablefinishes").html(options);
	});

}


});

