var toDiv;
var loadingDiv;
var variationCounter = 0;
var optionCounter = 0;
var divArray = new Array();
var uploadWindow;
var imageDirectory = "/uploads/images/";
var customError;
var fadeCanceled = false;
var fadeIncrement = 10;
var fadeTimerIncrement = 20;

var slidingDiv = function() {};
var slidingIncrement = .2;
var slidingTimerIncrement = 20;

var functionAfterLoad = "";

function validateSignup(form) {
	customError = "Also, make sure you email is entered correctly";
	
	//First lets see if they checked "Same as above"
	if(form.same.checked) copyAddress(form);
	MM_validateForm('fname','','R','lname','','R','email','','RisEmail','password','','R','password2','','R','company','','R','phone','','R','street','','R','city','','R','zip','','R','street2','','R','city2','','R','zip2','','R','description','','R');
	if(form.password.value != form.password2.value && document.MM_returnValue) {
		alert("Your passwords do not match.");
		form.password2.value = "";
		document.MM_returnValue = false;
		errorOnDiv('password');
		errorOnDiv('password2');
	}

}

function validateProduct(form) {
	customError = "Note: Weight is required to calculate shipping";
	MM_validateForm('name','','R','price','','R','weight','','R','description','','R','shippingDelay','','R');
	
	errorFixedOnDiv("newCategory");
	errorFixedOnDiv("category");
	
	if(document.MM_returnValue) {
		//Make sure they selected a category or at least added one
		if(form.category_id.selectedIndex == -1 && form.newCategory.value == "") {
			errorOnDiv("newCategory");
			errorOnDiv("category");
			alert("If you aren't adding a new category, you must select one from the list");
			document.MM_returnValue = false;
		}
	}
}

function starOver(prefix,id,rating,bigStars) {
	var size = "";
	if(!bigStars) size = "Small";

	for(var c=1;c<=5;c++) {
		var e = $(prefix+""+id+""+c);

	if(c<=rating) 
			e.src = "/media/star" + size + ".gif";
		else
			e.src = "/media/star" + size + "Disabled.gif";
	}
}

function setRating(prefix,id,rating,field) {
	field = $(field);
	field.value = rating;
}

function copyAddress(form) {
	form.street2.value = form.street.value;
	form.apt2.value = form.apt.value;
	form.city2.value = form.city.value;
	form.zip2.value = form.zip.value;
	form.state2.selectedIndex = form.state.selectedIndex;
}

<!--
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
	var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments,id;
  
	for (i=0; i<(args.length-2); i+=3) { 
		
		test=args[i+2]; val=MM_findObj(args[i]);
	
		if (val) { 
		
			nm=val.name; 
			id=val.id;
			
			errorFixedOnDiv(nm);
			
			if ((val=val.value)!="") {
		
				if (test.indexOf('isEmail')!=-1) { 
					p=val.indexOf('@');
		
					if (p<1 || p==(val.length-1)) { 
						errors+='- '+nm+' must contain an e-mail address.\n';
						errorOnDiv(nm);
					}
			
				} else if (test!='R') { 
					
					num = parseFloat(val);
		
					if (isNaN(val)) 
						errors+='- '+nm+' must contain a number.\n';
        
					if (test.indexOf('inRange') != -1) { 
						p=test.indexOf(':');
						min=test.substring(8,p); max=test.substring(p+1);
			
						if (num<min || max<num) {
							errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
							errorOnDiv(nm);
						}
				
					} 
				} 
			} else if (test.charAt(0) == 'R') {
				errors += '- '+nm+' is required.\n'; 
				errorOnDiv(nm);
			}
		}
	}
  
  if (errors) alert('Please make sure you fill out all required field (marked in red). ' + customError);
  document.MM_returnValue = (errors == '');
}
//-->

function errorOnDiv(id) {

	var style = fixStyle($(id));
	with(style) {
		
		//old settings if not already set
		if(!divArray[id]) {
			var oldDiv = new Object();
			oldDiv.fontWeight = fontWeight;
			oldDiv.color = color;
			divArray[id] = oldDiv;
		}
		fontWeight="bold";	
		color="#990000";
	}
}

function errorFixedOnDiv(id) {

	if(divArray[id]) {
		var style = fixStyle($(id));
		with(style) {
			var oldDiv = divArray[id];
			fontWeight = oldDiv.fontWeight;
			color = oldDiv.color;
		}
	}
	
	new Effect.Pulsate(id);
}

function fixStyle(element) {
	if(element.style) return element.style;
	return element;
}


function isVisible(element) {
	if(element.style) {
		if(element.style.display == "none") return false;
	} else {
		if(element.visibility == "hide") return false;
	}
	return true;
}

function hideToDiv() {
	hideShow($(toDiv),false);
}


function createDiv(inDiv, name, content) {
	
	var id = name;
	var div = document.create$("div");
	div.id = id;
	div.innerHTML = content;
	
	$(inDiv).appendChild(div);
	return div;
}

function removeDiv(inDiv, div) {
	//alert($(inDiv).childNodes.length);
	
	for(var c=0;c<$(inDiv).childNodes.length;c++) {
		if($(inDiv).childNodes[c].id == div) {
			$(inDiv).removeChild($(inDiv).childNodes[c]);
			break;
		}
	}
	//$(inDiv).removeChild($(div));
}


function screenWidth() {
	if(window.innerWidth) return window.innerWidth;
	if(document.body.parentNode.clientWidth) return document.body.parentNode.clientWidth;
	return window.body.clientWidth;
}

function screenHeight() {
	if(window.innerHeight) return window.innerHeight;
	if(document.body.parentNode.clientHeight) return document.body.parentNode.clientHeight;
	return window.body.clientHeight;
}



function fadeDivOut(div,to) {
	
}


function fadeDivIn(div,to) {

}

function setOpacity(div,op) {
	
	var style = fixStyle($(div));

	with(style) {
		opacity = op/100;
		filter = "alpha(opacity="+op+")";
	}
	
}

function hideShow(element, visible) {
	if(visible) {
		Effect.Appear(element);
	} else {
		Element.hide(element);
	}
}

//function to load page
function loadPage(page, div, ldiv) {
	
	$(ldiv).style.display = "block";
	
	new Ajax.Updater(div,page,{ onComplete: loadPageComplete(div,ldiv)});
}

function loadPageComplete(div,ldiv) {
	Effect.Fade(ldiv);
}

function postForm(form,url,func) {
		
	new Ajax.Request(url,{method:'post',postBody:getQueryStringFromForm(form)});
	
}

function getQueryStringFromForm(form) {
	
	var queryString = "";
	
	for(i=0; i<form.elements.length; i++) {
		queryString+= form.elements[i].name + "=" + escape(form.elements[i].value) +"&";
	}
	
	return queryString;
}


function postData() {
	var args = postData.arguments;
	var url = args[0];
	var queryString = "";
	
	for(var c=1;c<args.length;c++) {
		queryString+= args[c]+"="+escape($(args[c]).value)+"&";	
	}
	
	new Ajax.Request(url,{method:'post',postBody:queryString});

	
}


function addToCart(form) {
	
	var smallCartX = screenWidth()*.7;
	var smallCartY = -100;
	
//	$('productBorder').style.overflow = "hidden";
	$('productBorder').style.border = "1px solid black";
	//$('productBorder').style.height = "500px";
	
	if($('cartIcon').y) {
		
		$('productBorder').style.height = $('productSpacer').y - 180 + "px";


		smallCartY = $('cartIcon').y - parseInt($('productBorder').style.height)/2;
	}
	
	//alert($('productSpacer').y);
	Element.hide($('productContainer'));
	
//		setOpacity($('productContainer'),0);

//{x: smallCartX, y: smallCartY, mode: 'absolute'});
	new Effect.Parallel([new Effect.Move($('productBorder'),
							{x: smallCartX, y: smallCartY, mode: 'absolute',duration: 2}), 
						new Effect.Scale($('productBorder'),0,{duration:2}),
						new Effect.Fade($('productBorder'),{duration: 2 })],
						{ duration: 2, afterFinish: setTimeout('productAdded()',1500) });
	
	
	var queryString = getQueryStringFromForm(form);
	new Ajax.Request('/includes/cart/managecart.php/add/',{method:'post',postBody:queryString});
}


function productAdded() {
	loadPage('/message.php?title='+ escape('Product Added') +'&message=' + escape('You can either: <a href=/cart.php>View your cart</a> or <a href=/browse.php>Shop more</a>.'),'browseContent','loading');	
	setTimeout('refreshSmallCart()',1000);
}

function refreshSmallCart() {
	//loading cart
	new Ajax.Updater("smallCart","/includes/cart/smallcart.php", 
					 { onComplete: Effect.Pulsate($('smallCart'),
						{ afterFinish: function() { new Effect.Opacity($('smallCart'), { to:100 }); }}) });

}

function removeFromCart(id) {
	if(confirm("Are you sure you want to delete this product from the cart?")) {
		new Ajax.Request('/includes/cart/managecart.php/remove/'+id,{ onComplete: function() { refreshSmallCart(); refreshBigCart(); } });
	}
}

function updateCart(form) {
	var query = getQueryStringFromForm(form);
	new Ajax.Request("/includes/cart/managecart.php/update/",{ onComplete: function() { refreshSmallCart(); refreshBigCart(); }, method: 'post', postBody: query });
}

function refreshBigCart() {
	new Ajax.Updater("cartContainer","/includes/cart/bigcart.php", 
					 { onComplete: Effect.Pulsate($('shoppingCart'),
						{ afterFinish: function() { new Effect.Opacity($('shoppingCart'), { to:100 }); }}) });
}

function newVariation() {
	var d = "variation" + variationCounter;
	var div = createDiv("variationContainer",d, "");
	loadPage("/includes/productvariations.php?variationNum=" + variationCounter,d,"loading");
	variationCounter ++;
}

function removeVariation(vNum) {
	if(confirm("Are you sure you want to remove this variation and all it's options?")) {
		removeDiv("variationContainer","variation" + vNum);
	}
}

function newOption(vNum) {
	var d = "option" + vNum + "v" + optionCounter;
	var div = createDiv("optionsContainer" + vNum,d,"");
	loadPage("../includes/productoptions.php?variationNum=" + vNum + "&optionNum=" + optionCounter,d,"loading" + vNum);
	optionCounter ++;
}

function removeOption(vNum, oNum) {
	if(confirm("Are you sure you want to remove this options?")) {
		removeDiv("optionsContainer" + vNum,"option" + vNum + "v" + oNum);
	}	
}

function confirmAction(question, url) {
	if(confirm(question))
		window.location.href = url;
}

function uploadFile(returnField,type) {
	var previous = $(returnField).value;
	uploadWindow = window.open("/fileupload.php?field="+returnField+"&type="+type+"&previous="+previous,"UploadWindow","height=350,width=400,left=100,top=100,toolbar=no,menubar=no,toolbar=no");
}

function setUploadedImage(fieldName,imageName) {
	$(fieldName).value = imageName;
	var style = fixStyle($(fieldName + "ThumbSmall"));
	with(style) {
		backgroundImage = "url(" + imageDirectory + imageName + ")";
		backgroundPosition = "center center";
	}
}

function swapBackgroundImages(div1, div2) {
	var style1 = fixStyle($(div1));
	var style2 = fixStyle($(div2));
	
	var bg1 = style1.backgroundImage;
	var bg2 = style2.backgroundImage;
	
	style1.backgroundImage = bg2;
	style2.backgroundImage = bg1;
}

function imageWindow(div) {
	var style = fixStyle($(div));
	var image = style.backgroundImage;

	window.open("/image.php?image="+image.substring(4,image.length-1),"imageWindow","height=600,width=800,left=20,top=20,toolbar=no,menubar=no");	
}

function popupWindow(url,args) {
	window.open(url,"window",args);	
}

function getTop(div) {
	return fixStyle(div).top;
}

function getLeft(div) {
	return parseInt(fixStyle(div).left);
}

function setTop(div,value) {
	fixStyle(div).top = value + "px";
}

function setLeft(div,value) {
	fixStyle(div).left = value + "px";
}
