Function.prototype.if_confirmed = function(popname){
        var __method = this; //, args = arguments; //, temp = args.shift(), data = args.shift();
        return function(){
            var data = arguments[0] || {};
            var pop = $('#'+popname).modal();
            
            // IF YES
            pop.find('.yes').unbind('click').click(function(e){
                e.stopPropagation();
                pop.hide();
                return __method.apply(__method, [data]);
            });
        }
    };


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); } var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };

var FORM_DEFAULTS = [
    ['name','Name'],
    ['email','Email'],
    ['phone', 'Phone'],
    ['quantity', 'Qty']
]

jQuery.extend({
	// pops down the timed notifier
	notify : function(message, secs){
		var sTop = $(window).scrollTop();
		var panel = $('#notify');
		if (panel.data('timer'))
		  clearTimeout(panel.data('timer'));
		panel.css({'top':(sTop-200)+'px','opacity':'0'})
		  .find('.message').html(message).end()
		  .animate({'top':sTop+'px','opacity':'1'});
		panel.data('timer', setTimeout(function(){
		  //panel.animate({top:'-200px'});
		}, secs || 3000));
	},
	updateCartCount: function(count){
		$('span.cartcount').text(count);
	},
	
	 get_viewport: function() {
	 	var win=$(window);
        return {
            top:    win.scrollTop(),
            left:   win.scrollLeft(),
            width:  win.width(),
            height: win.height()
        }
    },
	notify2 : function(template, data, opts){
		opts = opts || {}
		var temp = $('#'+template);
		$.each(data, function(k,v){
			temp.find('.value_'+k).text(v);
		});
        var sTop = $(window).scrollTop();
        var panel = $('#notify');
        if (panel.data('timer'))
          clearTimeout(panel.data('timer'));
        panel.css({'top':(sTop-200)+'px','height':'0px'}).hide()
          .find('.content').append(temp.show()).end()
          .animate({'top':sTop+'px'}).show();
        panel.data('timer', setTimeout(function(){
          panel.animate({top:'-200px'}, function(){temp.hide(); if (opts.callback) opts.callback();});
        }, opts.secs || 3000));
    },
    updateCartCount: function(count){
        $('span.cartcount').text(count);
    },
	init_form: function(form, extras){
		$.each($.merge((extras || []), FORM_DEFAULTS), function(k,v){
			var f = form.find('[name='+v[0]+']').add_default(v[1]);
		});
	},
	init_ie_fix: function(el, f_cb, b_cal){
        if ($.browser.msie){
            el.find('select.warranty').focus(function(){
                $(this)
                    .data("origWidth", $(this).css("width"))
                    .css({"width": "auto"});
                if (f_cb) f_cb($(this));
                    
                    
            })
            .blur(function(){
                var self = $(this).css("width", $(this).data("origWidth"));
                if (b_cal) b_cal(self);
            })
            .change(function(){
                if (b_cal) b_cal($(this));
            });
            
        }
    },
    
    naptrack: function(observer, trigger, notes){
    	notes = typeof(notes)=='undefined' ? '' : '?n='+notes;
    	$('body').append('<div style="display: none"><img src="/naptrack/'+ observer +'/'+ trigger +'.png'+ notes +'" alt="NapTrack"/></div>');
    }
});

jQuery.fn.extend({
	// Adds default vals to textfields
	add_default: function(a){
		return $(this).each(function(){
			
			var obj =  $(this).blur(function(){
				var self = $(this);
				if (self.val()==''){
				     self.addClass('blank');
				     self.val(a);
				}
			})
			.focus(function(){
				var self = $(this);
				if (self.val()==a){
	                self.val('');
	                self.removeClass('blank');				
				}
			}).blur();
			
			obj.data('def_value', a);
//			obj.has_value=function(){
//				var self = $(this);
//				var has_val = self.val() != a;
//				self[has_val ? 'removeClass':'addClass']('err');
//				//self.css({'color':has_val?'#747474':'red'});
//				return has_val;
//			};
			if (obj.parents('form')){
				obj.parents('form').one('submit', function(){
					if (! obj.has_value()){
					    obj.val('');
					}
					    
				});
			}
		});
	},
	has_value: function(){ // This goes with add_default above
		  var self = $(this);
	        var has_val = self.val() != self.data('def_value');
	        self[has_val ? 'removeClass':'addClass']('err');
	        //self.css({'color':has_val?'#747474':'red'});
	        return has_val;
	},
	min_val: function(opts){
		$(this).each(function(){
			var self = $(this);
			opts = opts || {};
			self.data('min', parseInt(opts.val || self.attr('_min')));
            self.data('max', parseInt(opts.maxval || self.attr('_max')));
			return self.blur(function(){
	    		var val = parseInt($(this).val());
	    		var valid = val>=self.data('min');
	    		if (valid){
	    			if (self.data('max') && val > self.data('max')){
	    				valid = false;
	    			}
	    		}
	    		self[valid ? 'removeClass' : 'addClass']('error');
	    		if (valid && opts.valid_cb)
	    		  opts.valid_cb.apply(self);
	    		else if (opts.invalid_cb)
	    		  opts.invalid_cb.apply(self);
			});
		});
	},
	// adds ajax ability to form elements
	ajax_submit: function(cb, responseType, cond){
		responseType = responseType || 'json';
		this.submit(function(){
			var self = $(this);
			var has_price = self.find('select.variation').eq(0).data('has_price');
			function do_submit(){
				$.ajax({
		            url:self.attr('action'),
		            data:self.serialize(),
		            type:self.attr('method'), 
		            dataType:responseType,
		            complete: function(r){if (responseType=='json'){eval('r = '+r.responseText);} cb.call(self, r, has_price);}
		        });
			}
			if (! has_price && cond){
				if (! cond(self, do_submit)){
				    return false
				}
			}
			do_submit();
			return false;
		});
		return this;
	},
	add_to_cart: function(){
		$(this).each(function(){
			var self = $(this);
			self.ajax_submit(function(f, has_price){
		        if (has_price){
		           $.notify2('cart_success', {name:f.name, count:f.cart_count, total:to_format(f.cart_total)});
		           $.naptrack('checkout', 'ai', f.name);
		        } else{
		        	$.notify2('quote_success', {name:f.name});
		        }
		        $.updateCartCount(f.cart_count);
		    },
		    'json',
		    function(form, cb){
		        if ($.trim($.cookie('quotestocart')) == ''){
		        	var choice = $("#quote_choice").modal();
		        	function init(){
			            var pop = $('#quote_choice');
			        	if (pop.find('.quoteinfo').data('loaded')){
			        		return;
			        	}
			        	choice.quote_choice();
			            
			            pop.find('.submit').one('click', function(){
				                if ($.cookie('quotestocart')){
				                    pop.dismiss();
				                    cb();
				                }else{
				                    pop.find('.productname').val(form.find('input[name=productname]').val());
				                    pop.find('.quantity').val(form.find('input.qty_input').val());
				                    var sel = form.find('select.variation');
				                    pop.find('.variation').val(sel.val()).
				                    attr('name', sel.attr('name'));
				                    pop.find('form').ajax_submit(function(f){
		                    		    pop.find('.refresh').html(f.responseText);
				                    	if ('COMPLETE' == f.getResponseHeader('form_status')){
		                                     pop.dismiss();    		                    		
				                    	     $.notify2('quote_request_success', {});
				                    	}else{
				                    		init();
				                    	}
				                    },'html').
				                    submit();
				                }
			            });
			            pop.find('.quoteinfo').data('loaded', true);
		        	}
		        	init();
		            return false
		        }
		        return true;
		    }
		    
		    );
			
		});
	},
    paraexpander: function(){
        $(this).each(function(){
            var button = $(this).find('.more');
            var part = $(this).find('.part');
            var full = $(this).find('.full');
            var height = full.height();
            if (part.height() < height){
                button.show();
                full.css({height:part.height()});
                button.click( function(){
                        part.hide();
                        full.show().css({position:'relative'}).animate({height:height+'px'});
                        button.hide();
                        return false;   
                    });
                
            }                    
            
        });
    },
        
	quote_choice: function(){
		var self=$(this);
		//self.modal();
        self.find('input.cart').unbind('click').click(function(){
            $('div.quoteinfo').slideUp();
            $.cookie('quotestocart', 'true');
        });
        self.find('input.nocart').unbind('click').click(function(){
            $('div.quoteinfo').slideDown();
            $.cookie('quotestocart', null);
        });
        var formname  = self.find('input[name=name]').add_default('Name');
        var formemail = self.find('input[name=email]').add_default('Email');
        var formphone = self.find('input[name=phone]').add_default('Phone');
        //self.is_valid=function(){
       	//return $.cookie('quotestocart')!= null || (formname.has_value() && formemail.has_value()) // && formphone.has_value())
        //};
        return self;
	},
    modal: function(options, cb){
        var pop = $(this);
        var screen = $('#popscreen').css({opacity:0}).show();
        function init(){
            if (cb){cb(pop);} pop.center();
            pop.find('.close_pop a').live('click', function(){
                pop.dismiss();
                return false;
            });
        }
        init();
        $(window).resize(function(){pop.center(); screen.center(true);});
        $(window).scroll(function(){pop.center(); screen.center(true);});
        var vp = $.get_viewport();
        screen.width(vp.width + vp.left).height(vp.height + vp.top);
        screen.center(true).fadeTo('fast',.5);
        return pop.center().fadeIn();
    },
    dismiss: function(){
    	$(this).fadeOut();
    	$('#popscreen').fadeOut();
    	$(window).unbind('scroll').unbind('resize');
    },
	center: function(topalign){
	    var el = $(this);
	    var win = $(window);
	    var vtop = win.scrollTop();
	    if (topalign){
	    	el.css({top:vtop+'px'});
	    	return el
	    }
	    var pheight = el.height();
	    var pwidth = el.width();
	    var vheight= win.height();
	    var vwidth = win.width();
	    var comp_top = topalign?vtop:(vtop+(vheight /2)-(pheight/2));
	    el.css({
	        top:comp_top+'px',
	        left:(vwidth/2) - (pwidth/2)+'px'
	        });
	    return el;
	},
	submit_link: function(prepare){
		return this.live('click', function(){
			if (prepare) 
			 if (! prepare()) return false;
			$(this).parents('form').submit();
			return false;
		});
	},
	nav_tree: function(){
		var current = this.find('ul ul .current');
		if (current.length==0)
		  current = this.find('ul ul:first li');
		current.parents('ul').show();
		this.find('> ul > li a').click(function(){
			var sub = $(this).next('ul');
			if (sub.length){
				sub.toggle('slide');
			    return false;
			}
		});
	},
	// star widget
	favorite: function(){
		var on_text = "This product is one of your Favorites. Click to remove it.";
		var off_text = "Click to add this product to your favorites";
		var added_text = 'You have successfully added this product to your favorites.';
		var removed_text = 'You have successfully removed this product from your favorites.';
		var busy = false;
		$(this).each(function(){
			var self = $(this);
			var id  = self.find('.id').val();
			if ($.inArray(id, FAV_LIST)!=-1){
				self.addClass('selected');
				self.attr('title', on_text);
			}else{
				self.attr('title', off_text);
			}
			
		});
		var close_callback={callback:function(){
			busy = false;
		}};
		this.click(function(){
			if (FAV_NOAUTH){
			   $('.loginlink').eq(0).click();
			   return;
		    }
			if (busy) return;
			var self = $(this);
			if (self.hasClass('unauth')){
				alert('You need to log in in order to set your favorites');
				return;
				//document.location = '/login/?next='+document.location;
			}
			busy=true;
			var removing = self.hasClass('selected');
			$.ajax({
				url:'/favorites/'+(removing?'remove':'add')+'/ajax/',
				data:{product_id:self.find('input').val()},
				type:'post',
				dataType:'json',
				success: function(r){
					if (removing){
						$.notify2('favorite_note_remove', r,close_callback);
					}else{
						$.notify2('favorite_note', r, close_callback);
					}
					//$.notify2('favorite_note', {note:removing ? removed_text : added_text} );
					self.trigger(removing ? 'favorite_removed' : 'favorite_added');
				},
				error: function(r){
					alert('error');
					busy=false;
				}
			});
			self.toggleClass('selected');
		    self.attr('title', (!removing) ? on_text : off_text);	
		});
	},
	tab: function(cb){
        var loaded = [];
        var current = null;
		this.click(function(){
	        var self = $(this);
	        self.parents('.tabs').find('span').removeClass('active');
	        self.parents('span').addClass('active');
	        var tab = this.id.split('_')[1];
	        $('.tab_content').hide();
            var href = self.attr('href');
            var content = $('.tab_content.'+tab).show();
//            if ($.inArray(tab, loaded)==-1 && "#"!=href){
//        		loaded.push(tab);
//            	var loader = content.find('img.loader').show();
//		        $.ajax({
//		        	url: self.attr('href'),
//		        	dataType:'html',
//		        	success: function(r){
//		        		loader.hide();
//		        		var div = $(document.createElement('div'));
//		        		div.html(r);
//		        		div.appendTo(content);
//		        		if (cb) cb(content);
//		        	}
//		        });
//            }
	        return false;
	    }).eq(0).click();
	},
	update_value: function(val, highlight){
		this.text(val).effect("highlight", {color: highlight || 'yellow', speed:'slow'}, 8000);
	},
	temp_value: function(val){
		var self = this.hide().text(val).fadeIn('fast');
		setTimeout(function(){
			self.fadeOut();
		}, 3000);
	},
	product_selector: function(scope){
		var scope  = scope || $('body');
		var self = this.get(0);
		var jSelf = this;
		this.change(function(){
		  var has_price = $(self.options[self.selectedIndex]).hasClass('has_price');
		  jSelf.data('has_price', has_price);
		  scope.trigger('variant_changed', {has_price:has_price,value:jSelf.val()});  
		});
		this.change();
	},
	has_price: function(){
		return this.data('has_price');
	},
	cart_button: function(){
	   var self = this;
	   $('#product_add').bind('variant_changed', function(e, data){
	       self.attr('src', data.has_price ? '/static/images/addtocart.jpg' : '/static/images/requestquote.jpg'); 
	   });	
	},
    state_updater: function(state_selector, cb, url){
    	url = url || '/accounts/ajax_state_secure/';
        var self = this;
        this.live('change', function(){
            $(state_selector).load(url, {'country':$(this).val()}, function(){
            	if (cb) cb();
            	
            });
        });
    }
	});

var varRE = /\$\$(\w+)/g;

String.prototype.merge = function(data){
    return this.replace(varRE, function(a,b){
        return (data[b.split(' ')[0]] || '');
    })
    .replace(varRE, function(a,b,c,d){
        return data[b.split(' ')[0]] || '';
    });
};


function from_format(s){
	s = s.replace(/[\$\, ]/g,'')
	return parseFloat(s);
}
function to_format(num){
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	var sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	var cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

$(function(){
	$('#leftcontent').nav_tree();
	$('.fav_star:not(.noop)').favorite();
	
	$('.loginlink').click(function(){
		$('#loginpop').modal();
		return false;
	});
	$('.errorlink').click(function(){
	        $('#errorpop').modal();
		return false;
	});
	$('.estimatelink').click(function(){
		$('#zippop').modal();
		return false;
	});
	
	$('#login_user').add_default('Email Address');
	$('#login_pass').add_default('Password');
	$('#id_name').add_default('Name');
	$('#id_phone').add_default('Phone');
	$('#id_email').add_default('Email');
	$('#id_notes').add_default('Notes');
	$('#search input').add_default('Search by product, part #, or brand');
	
	/* home page */
	$('#quickquote, #buyback, a[href=#quickquote]').live('click',function(){
		var id = this.id || $(this).attr('href').split('#')[1];
		var pop = $('#'+id.split('_')[0]+'pop'); 
		pop.modal();
		if (! $(this).data('loaded')){
			
			$.init_form(pop, [['rental_length','Rental Length']]);
			var rental = pop.find('input[name=rental_length]');
			var submit = pop.find('a.submit').submit_link(function(){
				if (submit.data('clicked')) return false;
				submit.data('clicked', true);
				return true;
			});
			$(this).data('loaded', true);
			
			pop.find('input[type=radio]').change(function(){rental.css({display:this.value=='1' ? 'inline':'none'});});
			
			pop.find('form').ajax_submit(function(f){
				var cont =  ('COMPLETE' == f.getResponseHeader('form_status')) ? '.box2_cont_pop' : '.refresh';
                pop.find(cont).html(f.responseText);
                $.init_form(pop);
                submit.removeData('clicked');
            },'html');
		}
		
		return false;
	});
	
	/* search page */
	$('.perpage_select').change(function(){
        $(this).parents('form').submit();
        return false;
	});
});
