var loader = new Image();
loader.src = 'images/loader_red.gif';
function doNav(theUrl) {
	document.location.href = theUrl;
}
function pleaseWait(id) {
	$('pleaseWait'+id).show();
}
function showLoader() {
	$('loaderProcessing').style.display = 'block';
}
function deleteAccount(id) {
	if(confirm('Are you sure you want to delete this account?')) {
		doNav('/admin_accounts.php?action=process&section=delete&id='+id);
	}
	return false; 
}
function deleteParagraph(id,page,ret) {
	if(confirm('Are you sure you want to delete this paragraph?')) {
		doNav('/page_info.php?action=process&section=delete&id='+id+'&return='+ret+'&page='+page);
	}
	return false;
}
function deleteThis(id,type) {
	if(confirm('Are you sure you want to completely remove this '+type+'?')) {
		var url = $(id).href;
		doNav(url);
	}
	return false;
}
function submitForm(id) {
	$(id).submit();
	return false;
}
function refundOrder(id) {
	if(confirm('Are you sure you want to refund the total amount of this order to the customer?')) {
		doNav('/admin_orders.php?action=process&section=refund&id='+id);
	}
	closeLightBox();
	return false;
}
function refundPartialOrder(id) {
	var amount = prompt('Please enter the total amount you want to refund for this order:');
	if(amount) {
		doNav('/admin_orders.php?action=process&section=partialrefund&id='+id+'&amount='+amount);
	} else {
		closeLightBox();
	}
	return false;
}
function refundPopup(id) {
	showLightBox('Refund Order','<div>Which would you like to do?<br /><br /><input type="button" onclick="refundOrder(\''+id+'\');" value="Refund Full Amount" />&nbsp;&nbsp;&nbsp;<input type="button" onclick="refundPartialOrder(\''+id+'\');" value="Refund Partial Amount" /></div>')
}
function toggleOptions(id) {
	var divs = $$('div.optionsMenu');
	for(i=0;i<divs.length;i++) {
		if(divs[i]['id'] == 'optionsMenu'+id) {
			new Effect.toggle(divs[i]['id'],'appear',{duration:.2});		
		} else {
			new Effect.Fade(divs[i]['id'],{duration:.2});
		}
	}
	return false;
}
function showLightBox(title,message) {
	var viewport = document.viewport.getDimensions();
	var page = $(document.body).getDimensions();
	var width, height;
	if(viewport.width < page.width) {
		width = page.width;
	} else {
		width = viewport.width;
	}
	if(viewport.height < page.height) {
		height = page.height;
	} else {
		height = viewport.height;
	}
	doNav('#');
	$(document.body).insert('<div id="popupMessage" class="popupMessage"><div style="float:right;"><a href="#" onclick="return closeLightBox();"><img src="/images/icons/close.gif" border="0" alt="Close Window" /></a></div><h1>'+title+'</h1>'+message+'<br /><br /></div>');
	$(document.body).insert('<div id="overlay" class="overlay" style="width:'+width+'px;height:'+(height+60)+'px;position:fixed;"></div>');
	return false;
}
function closeLightBox() {
	if(Object.isElement($('popupMessage'))) {
		$('popupMessage').remove();
	}
	if(Object.isElement($('overlay'))) {
		$('overlay').remove();
	}
}
function displaySecurityCodeBox() {
	showLightBox('Security Code','A security code helps us to verify that you are the holder of this credit card.  Take a look at the image below to find the security code on your credit card.<br /><br /><div align="center"><img src="/thumb_gen.php?s=images/cv_card.jpg&w=280" /></div>');
	return false;
}
function loadShoppingCart() {
	new Ajax.Updater('cartDisplay','/ajax_cart.php?ajax=yes',{
		evalScripts:true
	});
}
function showError(message) {
	showLightBox('Error Encountered',message);
	return false;
}
function updateShoppingCart() {
	var elements = $('shoppingCartForm').serialize();
	new Ajax.Request('/shopping-cart?action=updatecart&ajax=yes&'+elements,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				showError(response);
			}
			loadShoppingCart();
		},
		onFailure:function() {showError('There was a problem communicating with the server. Please try again.');}
	});
	return false;
}
function removeProduct(id,options) {
	if(confirm('Are you sure you want to remove this item from your cart?')) {
		new Ajax.Request('/shopping-cart?action=remove&ajax=yes&id='+id+'&options='+options,{
			method:'get',
			onSuccess:function(transport) {
				var response = transport.responseText;
				if(response != '') {
					showError(response);
				}
				loadShoppingCart();
			},
			onFailure:function() {showError('There was a problem communicating with the server. Please try again.');}
		});
	}
	return false;
}
function continueCheckout() {
	updateShoppingCart();
	doNav('/checkout/billing');
	return false;
}
var AjaxRequest;
function lookupEmail() {
	if(AjaxRequest) {
		AjaxRequest.transport.abort();
	}
	var email = $('email').value;
	$('loadingEmail').innerHTML = '<img src="/images/loader_small.gif" border="0" align="absbottom" /> <span class="dkgray">Looking for previous orders. Please wait.</span>';
	$('loadingEmail').show();
	new Ajax.Request('/ajax_billing.php?email='+email,{
		method:'get',
		onCreate:function(request) {AjaxRequest = request;},
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				response = response.split('+');
				$('loadingEmail').innerHTML = '<span class="red">Some of your information was filled in from a previous order.</span>';
				$('first').value = response[0];
				$('last').value = response[1];
				$('address').value = response[2];
				$('city').value = response[3];
				$('state').value = response[4];
				$('zip').value = response[5];
				$('phone').value = response[6];
			} else {
				$('loadingEmail').hide();
			}
		},
		onFailure:function() {alert('There was a problem retrieving your information.');}
	});
}
function lookupCityState() {
	if(AjaxRequest) {
		AjaxRequest.transport.abort();
	}
	var zip = $('zip').value;
	new Ajax.Request('/ajax_billing.php?action=citystate&zip='+zip,{
		method:'get',
		onCreate:function(request) {AjaxRequest = request;},
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				response = response.split('+');
				$('city').value = response[0];
				$('state').value = response[1];
				$('zip').value = response[2];
			}
		},
		onFailure:function() {alert('There was a problem retrieving your information.');}
	});
}
function calculateShipping() {
	if(AjaxRequest) {
		AjaxRequest.transport.abort();
	}
	var subtotal = $('subTotal').value;
	$('shippingDisplay').innerHTML = '<img src="/images/loader_small.gif" border="0" alt="Loading"/>';
	var ship = $('shippingSelection').selectedIndex;
	ship = $('shippingSelection').options[ship].value;
	var zip = $('zipCode').value;
	var weight = $('shippingWeight').value;
	new Ajax.Request('ajax_shipping.php?ship='+escape(ship)+'&zip='+escape(zip)+'&weight='+escape(weight)+'&total='+escape(subtotal),{
		method:'get',
		onCreate:function(request) {AjaxRequest = request;},
		onComplete:function(transport) {
			var response = transport.responseText;
			if(response.match('international') || response.match('domestic')) {
				updateShippingOptions(response);
			} else if(response != '') {
				if(response.search('Error:') == '-1') {
					if(response == '0.00') {
						$('shippingDisplay').innerHTML = 'FREE';
					} else {
						$('shippingDisplay').innerHTML = '$'+(response*1).toFixed(2);
					}
					$('shippingValue').value = response;
					calculateSalesTax(zip);
					/*var newtotal = (subtotal*1)+(response*1);
										var tax = $('salesTax').value;
										if(tax != '') {
											newtotal = newtotal+(tax*1);
										}
										$('totalDisplay').innerHTML = '$'+newtotal.toFixed(2);*/
				} else if(response.search('Error: The requested service is invalid from the selected origin.') != '-1') {
					alert('We cannot ship to the zip code you have specified.  If you are in the US, please select a shipping method that does not say "International".  If you are in Canada, please select an International shipping method.');
					$('shippingDisplay').innerHTML = '-';
					calculateSalesTax(zip);
					//$('totalDisplay').innerHTML = '$'+subtotal.toFixed(2);
				} else {
					alert(response);
					$('shippingDisplay').innerHTML = '-';
					calculateSalesTax(zip);
					//$('totalDisplay').innerHTML = '$'+subtotal.toFixed(2);
				}
			} else {
				$('shippingDisplay').innerHTML = '-';
			}
		},
		onFailure:function() {alert('There was a problem retrieving shipping information.');}
	});
}
function updateShippingOptions(type) {
	var subtotal = $('subTotal').value;
	var weight = $('shippingWeight').value;
	$('shippingDisplay').innerHTML = '<img src="/images/loader_small.gif" border="0" alt="Loading"/>';
	new Ajax.Request('/ajax_shipping.php?action=options&type='+type+'&total='+subtotal+'&weight='+weight,{
		method:'get',
		onComplete:function(transport) {
			var response = transport.responseText;
			$('shippingOptions').innerHTML = response;
			calculateShipping();
		}
	});
}
var isCalculating = false;
function calculateShippingFinal() {
	$('shippingDisplay').innerHTML = '<img src="/images/loader_small.gif" border="0" alt="Loading" align="absmiddle"/> Retrieving shipping rates.';
	var subtotal = $('subTotal').value;
	var address = $('address').value;
	var city = $('city').value;
	var state = $('state').value;
	var zip = $('zip').value;
	var weight = $('shippingWeight').value;
	new Ajax.Request('/ajax_shipping.php?action=final&address='+escape(address)+'&city='+escape(city)+'&state='+escape(state)+'&zip='+escape(zip)+'&weight='+escape(weight)+'&total='+escape(subtotal),{
		method:'get',
		onCreate:function(request) {isCalculating = request;},
		onComplete:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				$('shippingDisplay').innerHTML = response;
			} else {
				$('shippingDisplay').innerHTML = 'Error: We could not find rates based on the information you entered.';
			}
			isCalculating = false;
		},
		onFailure:function() {alert('There was a problem retrieving shipping information.');}
	});
}
function allowShipping() {
	if(isCalculating) {
		$('pleaseWaitLoading').update('Please wait for the shipping rates to finish loading and then click continue.');
		return false;
	}
}
function calculateSalesTax(zip) {
	var subtotal = $F('subTotal');
	new Ajax.Request('/ajax_taxes.php?zip='+zip+'&subtotal='+subtotal,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				$('taxDisplay').update('$'+response+'<input type="hidden" name="salesTax" id="salesTax" value="'+response+'" />');
				$('taxRow').show();
			} else {
				$('taxDisplay').update('$0.00<input type="hidden" name="salesTax" id="salesTax" value="0.00" />');
				$('taxRow').hide();
			}
			updateTotal();
		},
		onFailure:function() {alert('There was a problem communicating with the server. Please hit refresh.');}
	});
}
function updateTotal() {
	var subtotal = $F('subTotal');
	var tax = $F('salesTax');
	var ship = $F('shippingValue');
	var total = '0.00';
	total = total*1;
	if(subtotal != '') {
		total = total+(subtotal*1);
	}
	if(ship != '') {
		total = total+(ship*1);
	}
	if(tax != '') {
		total = total+(tax*1);
	}
	$('totalDisplay').update('$'+total.toFixed(2));
}
function focusField(id,def) {
	if($(id).value == def) {
		$(id).value = '';
		$(id).setStyle({
			color:'#333'
		});
	}
}
function blurField(id,def) {
	if($(id).value == '') {
		$(id).setStyle({
			color:'#CCC'
		});
		$(id).value = def;
	}
}

function addOptionGrouping(id,i) {
	var id = $(id).identify();
	var newi = i;
	new Ajax.Request('/ajax_products.php?action=addgroup&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('optionsContainer').insert(response);
		},
		onFailure:function() {alert('There was a problem communicating with the server. Please try again.');}
	});
	newi++;
	$(id).onclick = function() {return addOptionGrouping(id,newi);};
	return false;
}
function removeOptionGrouping(i) {
	$('optiongrouping'+i).remove();
	return false;
}
function addOption(id,group,i) {
	var id = $(id).identify();
	var newi = i;
	new Ajax.Request('/ajax_products.php?action=addoption&group='+group+'&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('optiongrouping'+group).insert(response);
		},
		onFailure:function() {alert('There was a problem communicating with the server. Please try again.');}
	});
	newi++;
	$(id).onclick = function() {return addOption(id,group,newi);};
	return false;
}
function removeOption(id) {
	$('option'+id).remove();
	return false;
}
function addProductToOrder(i) {
	new Ajax.Request('/ajax_orders.php?action=addproduct&i='+i,{
		method:'get',
		onSuccess: function(transport) {
			var r = transport.responseText;
			showLightBox('Add Product To Order',r);
		},
		onFailure:function() {showError('We encountered an error while communicating with the server. Please try again.');}
	});
	return false;
}
function updateCartPrice(){
	$('cart-total').innerHTML = (parseFloat($('price').value) * $('qty').value).toFixed(2);
	$$('.required-input').each(function(s) {
	    if($(s) != undefined){	    
		var price = $(s).value.match(/[0-9]+[.][0-9]+/);
		if(price == 'NaN' || price == false || price == null){
			price = 0;
		}
		$('cart-total').innerHTML = (parseFloat($('cart-total').innerHTML) + (parseFloat(price) * parseFloat($('qty').value))).toFixed(2);
		if(!$(s).value.match(/click to select/i) && $(s).value != '' && $(s).value != 0){
			$(s).setStyle("color: #333;");
		}
	    }
	});
}
function checkRequiredFields(a){
	var error = "";
	$$('select.required-input').each(function(e){
	    if(e.value.match(/click to select/i) || e.value == ''){
		$(e.id).setStyle("color: #f00;");
		a.stop();
		error = "Please make a selection for each option";
	    }
	});
	if($('qty').value <= 0){
	    $('qty').setStyle("color: #f00;");
	    error = 'Please enter a Quantity';
	    a.stop();
	}else{
	    $('qty').setStyle("color: #333;");
	}
	if(error != ""){
	    alert(error);
	}
}
function getProductDetails(i) {
	var id = $F('productname');
	new Ajax.Request('/ajax_orders.php?action=getdetails&id='+id+'&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			$('productDetails').update(r);
		},
		onFailure:function() {showError('We encountered an error while communicating with the server. Please try again.');}
	});
	return false;
}
function insertProduct(i) {
	var newi = i;
	var elements = $('productForm').serialize();
	new Ajax.Request('/ajax_orders.php?action=insertproduct&'+elements+'&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			$('productTable').insert(r);
			closeLightBox();
			updateAdminOrder();
		}
	});
	newi++;
	$('addProductLink').onclick = function() {'return addProductToOrder(newi);';};
	return false;
}
function removeAdminOrderProduct(id) {
	$('product'+id).remove();
	updateAdminOrder();
	return false;
}
function updateAdminOrder() {
	setTimeout(function() {
		var elements = $('adminOrderForm').serialize();
		new Ajax.Request('/ajax_orders.php?action=updateadmincart&'+elements,{
			method:'get',
			onSuccess:function(transport) {
				var r = transport.responseText;
				$('adminCartDisplay').update(r);
			},
			onFailure:function() {showError('There was a problem communicating with the server. Please try again.');}
		});
	},200);
	return false;
}
function quickAddToCart(id) {
	new Ajax.Request('/shopping-cart?action=quickaddpopup&id='+id,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			showLightBox('',response);
		},
		onFailure:function() {showError('There was a problem communicating with the server. Please try again.');}
	});
	return false;
}
function addCategory(e){
    var my_div = '<span class="add-category-input"><input type="text" id="new_cat_value"/> <input type="button" value="Create" onclick="createCategory(this)"></span>';
    e.insert({before:my_div});
    e.hide();
    return false;
}
function createCategory(e) {
    var cat_name = $('new_cat_value').value;
    if(cat_name != ''){
        var element = "<div class='collapsable category-name'>[<span class='toggle-state'>new</span>]&nbsp;<span>"+cat_name+"</span><div class='cat-del'>&nbsp;</div></div><div class='category-tags'><a class='add-tag' href='' onclick='return addTag(this,\""+cat_name+"\");' class='adminLink'><img src='/images/icons/add.png' align='absbottom' border='0' /> Add Tag</a></div>";
        element += "<div style='clear: left;'></div>";
    }
    e.up().next().show();
    e.up().replace(element);
    return false;
}
function addTag(e,cat){
    var my_div = '<span class="add-tag-input"><input type="text" id="new_tag_value"/> <input type="button" value="Create" onclick="createTag(this,\''+cat+'\')"></span>';
    e.insert({before:my_div});
    e.hide();
    return false;
}
function createTag(e,cat){
    var my_checkbox = '';
    if($(e).previous().value != ''){
        my_checkbox = '<span class="tag-span"><input type="checkbox" checked name="tags['+cat+'][]" value="'+e.previous().value+'"><label for="">'+e.previous().value+"</label><div class='tag-del'>&nbsp;</div></span>";
    } 
    e.up().next().show();
    e.up().replace(my_checkbox);
    return false;
}
Event.observe(document,'dom:loaded',function(){
    $$('.collapsable.collapsed').each(function(e){
       e.next().hide();
       e.down().innerHTML = "+";
    });
    $$('.collapsable').invoke('observe','click', function(){
        if(this.next().style.display == 'none'){
            this.next().appear({duration: .3});
            this.down().innerHTML = "-";
        }else{
            this.next().fade({duration: .3});
            this.down().innerHTML = "+";
        }
    });
    $$('.tag-del').invoke('observe','click', Delete_Tag);
    $$('.cat-del').invoke('observe','click', Delete_Cat);
    $$('.filter-options').invoke('observe','click', Filter_Clicked);
    $$('.customer-type .hover').invoke('observe','mouseover', Type_Hover, this);
    $$('.customer-type .hover').invoke('observe','mouseout', Type_Out);
});
function Type_Hover(e){
    var img_id = this.id;
    mouseX = Event.pointerX(e) - this.cumulativeScrollOffset()[0];
    mouseY = Event.pointerY(e) - this.cumulativeScrollOffset()[1];
//    alert('x: '+mouseX+', y: '+mouseY);
    $('type_'+img_id).style.top = mouseY-20 +'px';
    $('type_'+img_id).style.left = mouseX-320 +'px';
    $('type_'+img_id).style.display ='block';
}
function Type_Out(){
    var img_id = this.id;
    $('type_'+img_id).style.display ='none';
}
function Delete_Tag(){
    if(confirm("Are you sure you want to PERMANENTLY delete the tag labeled: '"+this.previous().innerHTML+"'")){
        new Ajax.Request('/ajax_admin_products.php?action=delete&tag_id='+this.previous().previous().value,{
		method:'get',
		onFailure:function() {showError('There was a problem communicating with the server. Please try again.');}
	});
        this.up().hide();
    }else{
        return false;
    }
}
function Delete_Cat(){
    if(confirm("Are you sure you want to PERMANENTLY delete the category labeled: '"+this.previous().innerHTML+"'")){
//        alert(this.id);
//        return true;
        new Ajax.Request('/ajax_admin_products.php?action=delete&cat_id='+this.id,{
		method:'get',
		onFailure:function() {showError('There was a problem communicating with the server. Please try again.');}
	});
        this.up().hide();
    }else{
        return false;
    }
}
var filterActivity = {
	bg:'filterActivityBG',
	loader:'filterActivityLoader',
	exists:false,
	show:function() {
		if(!this.exists) {
			this.create();
		}
		$(this.bg).show();
		$(this.loader).show();
	},
	hide:function() {
		$(this.bg).hide();
		$(this.loader).hide();
	},
	create:function() {
		var bg = new Element('div',{id:'filterActivityBG'}).setStyle({
			position:'absolute',
			background:'#000',
			width:'100%',
			height:'100%',
			top:0,
			left:0,
			zIndex:10000,
			display:'none'
		}).setOpacity(0.5);
		document.body.insert(bg);
		
		var loader = new Element('img',{id:'filterActivityLoader',src:'/images/loader_on_black.png',border:0,alt:'Loading...'}).setStyle({
			position:'absolute',
			zIndex:10001,
			top:'50%',
			left:'50%',
			margin:'-32px 0 0 -32px',
			display:'none'
		});
		document.body.insert(loader);
	}
};
function Filter_Clicked(){
	filterActivity.show();
    if( ! this.hasClassName('filter-selected')){
        this.addClassName('filter-selected');
    }else{
        this.removeClassName('filter-selected');
    }
    showCheckedProducts();
}
function showCheckedProducts(){
    var string = '';
    var last_div_id = 0;
    var shown_any = false;
    $$('.filter-options').each(function(filter){
        if(filter.hasClassName("filter-selected")){
            var div_id = filter.readAttribute('id');
            if(last_div_id != div_id){
                if(last_div_id > 0){
                    string += "),(";
                }else{
                    string += '(';
                }
                last_div_id = div_id;
                
            }else{
                string += '|';
            }
            string += "TAG-"+filter.down().id;
        }
    });
    if(string != ''){
        string += ")";
        $$('.productBoxArray').each(function(productBox){
            var splits = string.split(',');
            var show = true;
            splits.each(function(e){
                var pattern = new RegExp(e);
                if(! pattern.test(productBox.className)){
                    show = false;
                }
            });
            if(show == true){
                shown_any = true;
                productBox.appear({duration: .8});
            }else{
                productBox.fade({duration: .2});
            }
        });
    }
    if( ! shown_any && string == ''){
        $$('.productBoxArray').each(function(productBox){
            productBox.appear({duration: .8});
        });
    }
    if ( ! shown_any && string != '') {
        setTimeout("$('noProductsFound').show()", 300);
    }else{
         $('noProductsFound').hide();
    }
	setTimeout(function() {
		filterActivity.hide();
	},500);
}
function addRelatedProduct(e){
    if($(e).previous().selectedIndex == -1){
        return false;
    }
    var related_id = $(e).previous().options[$(e).previous().selectedIndex].value;
    var product_id = $('product_id').value;
    new Ajax.Request('/ajax_admin_products.php?action=add-related&related_id='+related_id+'&product_id='+product_id,{
        method:'get',
        onCreate:function() {$('test').src = '/images/loader_small.gif';},
        onSuccess:function(transport) {
            var response = transport.responseText;
            if(response != '') {
                $('related-products').insert({after:response});
            }
        },
        onComplete: function() {
            $('test').src = '/images/icons/add.png';
            $(e).previous().options[$(e).previous().selectedIndex].remove();
        },
        onFailure:function() {alert('There was a problem retrieving your information.');}
    });
    return false;
}
function deleteRelatedProduct(e,related_id){
    var product_id = $('product_id').value;
    if(confirm('Are you sure you want to remove this related product?')){
        new Ajax.Request('/ajax_admin_products.php?action=delete-related&related_id='+related_id+'&product_id='+product_id,{
            method:'get',
            onSuccess:function() {
                $(e).remove();
            },
            onFailure:function() {alert('There was a problem retrieving your information.');}
        });
    }
    return false;
}

function generateSlug() {
	if($F('slug') == '') {
		$('slug').value = slugify($F('name'));
	}
}

function deletePreviousSlug(id) {
	new Ajax.Request('/ajax_products.php?action=delete-previous-slug&id='+id,{
		onSuccess:function() {
			$('slug_'+id).fade();
		},
		onFailure:function(){ alert('There was a problem deleting this slug. Please try again.'); }
	});
	return false;
}

function slugify(text) {
	var f = text.underscore().replace(/[ \-]/g,'_').replace(/\W/g,'').replace('___','_').dasherize().toLowerCase();
	return f;
}
