// JavaScript Document
var _global = window.document;
_global.overlay = 0;
var page = 1;

function openPop(url,praia,l,h,scroll) {
	window.open(url,praia,"resizable=1status=yes,scrollbars=" + scroll + ",toolbar=no,location=no,menu=-no,width=" + l + ",height=" + h + "");
}

function deleteItem(location)
{
	var answer = confirm("Are you sure you want to delete this item from the " + location + "?");
	if(answer)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function validate_required(fieldID, title)
{
	value = document.getElementById(fieldID).value;
	if (value==null||value=="")
	{
		requiredList += "  - " + title + '\n';
		return false;
	}
	else
	{
		return true;
	}
}

function validate_email(fieldID)
{
	value = document.getElementById(fieldID).value;
	apos=value.indexOf("@");
	dotpos=value.lastIndexOf(".");
	if (apos<1||dotpos-apos<2) 
	{
		requiredList += '\n' + "The email address provided is invalid" + '\n';
		return false;
	}
	else
	{
		return true;
	}
}

function checkPay()
{
	requiredList = "";

	validate_required("card_type", "card type");
	validate_required("x_card_num", "card number");
	validate_required("month", "card expiry month");
	validate_required("year", "card expiry year");
	
	if(requiredList != "")
	{
		errorString = "The following fields are required:\n\n" + requiredList;
		alert(errorString);
		return false;
	}
	else
	{
		return true;
	}
}

function checkCustomer()
{
	requiredList = "";

	validate_required("x_first_name", "first name");
	validate_required("x_last_name", "last name");
	validate_required("x_email", "email address");
	validate_required("x_address", "street address");
	validate_required("x_city", "city");
	validate_required("x_zip", "zip");
	validate_required("x_country", "country");
	validate_email("x_email");
	
	if(requiredList != "")
	{
		errorString = "The following fields are required:\n\n" + requiredList;
		alert(errorString);
		return false;
	}
	else
	{
		return true;
	}
}

function checkShop()
{
	requiredList = "";

	validate_required("category", "category");
	validate_required("title", "title");
	
	var body = null;
	var oEditor = FCKeditorAPI.GetInstance('body');
	if(oEditor) { body = oEditor.GetXHTML(true); }
	if (body==null||body=="")
	{
		requiredList += "  - body" + '\n';
	}
	
	validate_required("short_desc", "short description");
	
	var main = document.getElementById("filepath_main").value;
	if (main==null||main=="")
	{
		requiredList += "  - main image" + '\n';
	}
	var large0 = document.getElementById("filepath_large0").value;
	if (large0==null||large0=="")
	{
		requiredList += "  - main large image" + '\n';
	}
	
	validate_required("materials", "materials");
	validate_required("dimensions", "dimensions");
	validate_required("features", "features");
	validate_required("price", "price");

	if(requiredList != "")
	{
		errorString = "The following fields are required:\n\n" + requiredList;
		alert(errorString);
		return false;
	}
	else
	{
		return true;
	}
}

function next_previous_junk()
{
	$("#previousButton").hide();
	$("#nextButton").hide();
	
	var no_pages = $(".page").length;
	
	if(no_pages > 1)
	{
		$("#nextButton").show();
	}
	
	$(".page").each(function(i){
		//hide everything but first page
		if(i != 0)
		{
			$(this).hide();
		}
	});
	
	$("#nextButton").click(function(){
		page++;
		//alert(page);
		$(".page").hide();
		$(".page:eq(" + (page - 1) + ")").show();
		
		$("#nextButton").show();
		$("#previousButton").show();
		
		if(page == 1)
		{
			$("#previousButton").hide();
		}
		else if(page == no_pages)
		{
			$("#nextButton").hide();
		}
	});

	$("#previousButton").click(function(){
		page--;
		$(".page").hide();
		$(".page:eq(" + (page - 1) + ")").show();
		
		$("#nextButton").show();
		$("#previousButton").show();
		
		if(page == 1)
		{
			$("#previousButton").hide();
		}
		else if(page == no_pages)
		{
			$("#nextButton").hide();
		}
	});
}

function next_previous()
{
	$(".previous").hide();
	$(".next").hide();
	
	$("a[rel]").each(function(i){
		// show and hide the next / previous controls
		$(this).click(function(){
			if((i == 0) && (_global.overlay > 0))
			{
				//alert("hide previous");
				$(".previous").hide();
				$(".next").show();
			}
			else if(i == (_global.overlay - 1))
			{
				//alert("hide next");
				$(".previous").show();
				$(".next").hide();
			}
			else
			{
				//alert("show both");
				$(".previous").show();
				$(".next").show();
			}
		});
				
		// setup the call to each overlay
		string = "[rel='#overlay" + i + "']";									 
		_global["api" + i] = $("a" + string).overlay({expose: '#000000', speed: 'slow', fadeInSpeed: 'slow', api:true});
		_global.overlay++;
		
	});
	
	// next control setup
	$(".next").click(function(){
		control = $(this);
		wrapper = control.parent();
		
		wrapperID = wrapper.attr("id");
		currentOverlayNumber = parseInt(wrapperID.replace("overlay",""));
		newOverlayNumber = currentOverlayNumber + 1;
		
		_global["api" + currentOverlayNumber].close();
		_global["api" + newOverlayNumber].load();
		
		if(newOverlayNumber == (_global.overlay - 1))
		{
			$(".previous").show();
			$(".next").hide();
		}
		else
		{
			$(".previous").show();
			$(".next").show();
		}
	});

	// previous control setup
	$(".previous").click(function(){
		control = $(this);
		wrapper = control.parent();
		
		wrapperID = wrapper.attr("id");
		currentOverlayNumber = parseInt(wrapperID.replace("overlay",""));
		newOverlayNumber = currentOverlayNumber - 1;
		
		_global["api" + currentOverlayNumber].close();
		_global["api" + newOverlayNumber].load();
		
		if(newOverlayNumber == 0)
		{
			$(".previous").hide();
			$(".next").show();
		}
		else
		{
			$(".previous").show();
			$(".next").show();
		}
	});
}

function loadCategoryList(element)
{
	function loadItem(e)
	{
		var content_id = e.value;
		$("#item").html("Loading...");
		
		$.ajax({
			type: "GET",
			cache: "false",
			url: "../item.php",
			data: "content_id=" + content_id,
			success: function(html){
				var data = $(html).html();
				
				$("#item").html(data);
			}
		});
	}
	
	var jHandle = $(element);
	$("#items").html("Loading...");
	$("#item").html("");
	
	$.ajax({
		type: "GET",
		cache: "false",
		url: "../items.php",
		data: "category=" + jHandle.val(),
		success: function(html){
			var data = $(html).html();
			
			if(data.length > 1)
			{
				$("#items").html(data);
				
				$("#shopItems").change(function(){
					loadItem(this);
				});		
			}
			else
			{
				$("#items").html("No results for this category.");
			}
		}
	});
}

function addToCart(object)
{
	object.click(function(e){
		e.preventDefault();
		
		// product details
		var title = escape( $("#title").val() );
		var content_id = $("#content_id").val();
		var price = $("#price").val();
		var quantity = $("#quantity").val();
                var zip = $("#zip").val();
                var country = $("#country").val();
                if(zip == ""){
                    alert("You must enter a zip code.");
                    return;
                }
		
		//update cart
		$.ajax({
			type: "GET",
			cache: "false",
			url: "../../../../cart.php",
			data: "refresh=1&add=1&title=" + title + "&content_id=" + content_id + "&price=" + price + "&quantity=" + quantity +"&zip=" +zip + "&country="+country,
			success: function(html){
                                //alert(html);
                                if(html == "Error")
                                {
                                    alert("Invalid Shipping Information.");
                                    return;
                                }
				$("#cartnumber").html(parseInt($('#cartnumber').text(), 10)+1);
				$("#added").fadeIn(600);
				
				// rebind remove control because it was in replaced html
				removeFromCart($(".delete"), "product");
			}
		});
	});
}

function removeFromCart(object, location)
{
	object.each(function(i){
		$(this).click(function(e){
			e.preventDefault();
			
			var content_id = $(this).attr('id').replace("content_id_","") ;
			
			if(location == "shop")
			{
				var myURL = "../cart.php";
				var myData = "remove=1&content_id=" + content_id;
			}
			else if(location == "product")
			{
				var myURL = "../../../../cart.php";
				var myData = "refresh=1&remove=1&content_id=" + content_id;
			}
			else
			{
				var myURL = "../cart.php";
			}
			
			//update cart
			$.ajax({
				type: "GET",
				cache: "false",
				url: myURL,
				data: myData,
				success: function(html){
					$("#cartContainer").html(html);
					window.location.reload(true);
					
					// rebind remove control because it was in replaced html
					removeFromCart($(".delete"), location);
				}
			});
		});
	});
}
window.$ = window.jQuery;
$(function() {

	// junkyard page
	if($(".junkyard") != null)
	{
            if($(".junkyard").length > 0)
            {
		next_previous();
		next_previous_junk();
            }
	}
	
	// product page
	if($("input[name='page']").val() == "product")
	{
		next_previous();
		addToCart($("#addCart"));
		removeFromCart($(".delete"), "product");
	}
	
	// shop browse page
	if($("input[name='page']").val() == "shop")
	{
		removeFromCart($(".delete"), "shop");
	}
	
	// shop checkout page
	if($("input[name='page']").val() == "checkout")
	{
		removeFromCart($(".delete"), "checkout");
	}
	
	$("#shopCategory").change(function(){
		loadCategoryList(this);
	});

        $(".jvid .thumb").click(function(){
           $(this).siblings("a").click();
        });
	
	if($("#main.home").length > 0)
        {
            var currentPicture = $('#main.home .panel div:first');
            function getRandElement()
            {
                var randomnumber=Math.floor(Math.random()*9);
                return $('#item_'+randomnumber);
            }
            window.nextPic = function(){
                setTimeout('nextPic()', 1000);
                return (function(){

                    var ids = [];
                    $.each($('#main.home .panel div a'), function(){
                       ids.push(($(this).attr('rel')));
                    });

                    var id_string = ids.join(",");
                    $(currentPicture).animate({"opacity" : 0}, 1000, function(){
                        $.get('/rand_item.php?not_in=' + id_string, function(data){
                            $(currentPicture).html(data);
                                $(currentPicture).animate({"opacity" : 1}, 1000, function(){
                                    var nextPicture = getRandElement();
                                    while(currentPicture == nextPicture)
                                    {
                                        nextPicture = getRandElement();
                                    }
                                    currentPicture = nextPicture;
                                    setTimeout('nextPic()', 3000);
                                });
                        });
                    });
                });
            }();
      }
});
