
// taken from http://snipplr.com/view/7345
function add_commas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
	x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

var cart = new function()
    {
	this.curent_remove_id;
	this.locked;
	this.current_row;
	var self = this;

	this.initRemove = function(id)
	{
	    self.locked = 0;
	    self.current_remove_id = id;	    
	};

	this.continueRemove = function()
	{
	    var $remove_image = $('#delete_'+self.current_remove_id);
	    var $row = $remove_image.parent().parent();
	    self.current_row = $row;
	    $row.fadeOut("slow", self.recalculateTotal);	    
	};

	this.recalculateTotal = function()
	{	  
	    self.current_row.css("display", "none");
	    
	    var total = 0;
	    $('.line span').each(function(){
		    $this = $(this);
		    if($this.parent().parent().css("display") != "none")
			{
			    total += parseFloat($this.text().replace(",", ""));
			}
		});
	    total = add_commas(total.toFixed(2));
	    $('#totalPrice span').empty().append(total);
	    self.locked = 0;
	};

	this.remove = function()
	{
	    self.locked = 1;	    
	    $.ajax({
		    url: window.location.toString(),
		    timeout: 5000,
		    type: 'GET',
		    data: 'id='+self.current_remove_id,
		    dataType: 'json',
		    success: function(data, textStatus){			
			self.continueRemove();
		    },
		    error: function(x, txt, e){
			alert(txt);			
		    }
		});		
	};


    };

var help = new function()
    {
	this.on = false;
	this.speed = 500;
	var self = this;

	this.init = function()
	{
	    if($('#help #help_inner').css('display') == "block")
		{
		    self.on = true;
		}
	};

	this.continueToggle = function()
	{	    
	    if(!self.on)
		{
		    $('#help #help_inner').slideDown(self.speed, self.contentIn);
		}
	    else
		{		    
		    self.contentOut();
		}
	};

	this.toggle = function()
	{
	    $.ajax({
		    url: "http://"+WEB_ROOT+PUBLIC_DIR+"/admin/toggle_help",
		    timeout: 5000,
		    type: 'GET',
		    dataType: 'json',
		    success: function(data, textStatus){			
			self.continueToggle();
		    },
		    error: function(x, txt, e){
			alert(txt);			
		    }
		});		    		
	};

	this.contentIn = function()
	{
	    $('#help #help_inner div').fadeTo(self.speed/3, 1, function(){
		    self.on = true;
		});
	};

	this.contentOut = function()
	{
	    $('#help #help_inner div').fadeTo(self.speed/3, 0, self.hideHelp);

	};

	this.hideHelp = function()
	{
	    $('#help #help_inner').slideUp(self.speed, function(){
		    self.on = false;
		});
	};


	/*
	    if(!self.on)
		{

		}
	    else
		{
		    $('#help #help_inner div').hide();
		    self.on =false;
		}
	*/
	

    };


var edit_box = new function()
    {
	this.current_text = '';
	this.old_text = '';
	this.parent_element;
	this.locked = 0;
	this.id = 0;
	
	var self = this;

	this.calculateTotal = function()
	{
	    // added for product variants
	    var price = $('#price').text();
	    var total = (parseFloat(price) + parseFloat(self.current_text)).toFixed(2);	    
	    $('#total_'+self.id).empty().append('&pound;'+total);	    
	};

	this.init = function(p, t, id)
	{
	    self.parent_element = p;
	    self.current_text = t;
	    self.old_text = self.current_text;	    
	    self.id = id;	    
	};

	this.error = function(msg)
	{
	    alert(msg);
	    self.current_text = self.old_text;
	    self.leave();
	};

	this.enter = function()
	{	  
	    self.locked = 1;
	    $("#button_"+self.id+" img").show();
	    self.parent_element.empty().append('<input type="text" id="option_'+self.id+'" value="'+self.current_text+'" />');			
	    var input = self.parent_element.find('input');
	    input.focus();
	    input.select();
	    input.bind('blur', function(e){
		    var $this = $(this);
		    self.current_text = $this.attr('value');
		    
		    if(self.current_text == self.old_text)
			{
			    self.leave();
			}
		    else
			{
			    
			    $.ajax({
				    url: window.location.toString(),
					timeout: 5000,
					type: 'POST',
					dataType: 'json',
					data: 'id='+self.id+'&value='+parseFloat(self.current_text).toFixed(2),
					success: function(data, textStatus){			
					if(data < 0)
					    {
						self.error('server error');
					    }
					else if(data == 0)
					    {
						self.error('invalid option');
					    }
					else
					    {
						self.leave();
						self.calculateTotal();
					    }								    						    
				    },
					error: function(x, txt, e){
					self.error(txt);				
				    }
				});		    
			}
		});
	    
	};

	this.leave = function()
	{
	    self.locked = 0;
	    $("#button_"+self.id+" img").fadeOut();
	    var amount = parseFloat(self.current_text).toFixed(2);
	    self.parent_element.empty().append('&pound;<span class="option" id="option_'+self.id+'">'+amount+'</span>');			
	    var span = self.parent_element.find('span');	    
	    span.bind('click', function(e){
		    var $this = $(this);
		    if(self.locked == 0)
			{
			    self.init($this.parent(), $this.text(), $this.attr('id').split('_')[1]);
			    self.enter();
			}
		});
	};
    };



var properties = function()
{
    /*
      $('#properties fieldset legend').bind('click', function(e){
      e.preventDefault();
      var $this = $(this);
      toggle_p($this);
      });
    */
    /*
    $('#properties form span.option').bind('click', function(e){
	    var $this = $(this);
	    if(edit_box.locked == 0)
		{
		    edit_box.init($this.parent(), $this.text(), $this.attr('id').split('_')[1]);
		    edit_box.enter();
		}
	});
    */

    $('#variants .edit').bind('click', function(e){
	    var $this = $(this);
	    if(edit_box.locked == 0)
		{
		    edit_box.init($this.parent(), $this.text(), $this.attr('id').split('_')[1]);
		    edit_box.enter();
		}
	});


};



$(document).ready(function(){

        $('#op_right form').change(function(){
                this.submit();
            });
        //      alert(1);                                                                                                                                            

	
	if($('.highslide-gallery').length > 0)
	    {
		hs.showCredits = false;
		hs.graphicsDir = 'http://'+WEB_ROOT+PUBLIC_DIR+'/graphics/';
		hs.align = 'center';
	hs.transitions = ['expand', 'crossfade'];
	hs.outlineType = 'rounded-white';
	hs.wrapperClassName = 'controls-in-heading';
	hs.fadeInOut = true;
	//hs.dimmingOpacity = 0.75;

	// Add the controlbar
	if (hs.addSlideshow) hs.addSlideshow({
		//slideshowGroup: 'group1',
		interval: 5000,
		repeat: false,
		useControls: true,
		fixedControls: false,
		overlayOptions: {
			opacity: 1,
			position: 'top right',
			hideOnMouseOut: false
		}
	});
	    }

	if($('#variants .edit').length > 0)
	    {
		properties();
	    }

	if($('#help').length > 0)
	    {
		help.init();
		$('#help_tab').bind("click", function(e){
			e.preventDefault();
			help.toggle();
		    });
	    }

	/*
	if($('.product #printDesc').length > 0)
	    {
		var $desc = $('.product #printDesc > p');
		var text = $desc.text();
		text = 'Descripion: '+text;
		$desc.empty().append(text);		
	    }
	*/

	if($('#checkoutTable .delete').length > 0)
	    {
		$('#checkoutTable .delete img').bind("click", function(e){
			e.preventDefault();
			var $this = $(this); 
			var $parent = $this.parent();
			var id = $parent.attr('id').split('_')[1];
			if(!cart.locked)
			    {
				cart.initRemove(id);
				cart.remove();
			    }
		    });
			
	    }	

	if($('form#paypal').length > 0)
	    {
		var f = $('form#paypal');
		f.submit();
	    }

	
	$('a.back').bind("click", function(e){
		e.preventDefault();
                history.go(-1);
            });


    });

