var productCount = new Object();
var toggleCount = 0;
var copyInfoCount = 0;
var formFields = [ "Name", "Address", "City", "State" , "Zip", "Phone", "Fax"];
var requiredFormFields = [ "Name", "Address", "City", "State" , "Zip", "Phone"];

function getNextAttribute(rowId,name,value)
{
    var id = rowId.split("-");
    id = id[1];
    var numChildren = $("#attributeList-"+id+" > div").size();
    var attributes = $("#attribId-"+id).val();//+id);
    var attributesArray = attributes.split(",");
    var productName = $("#nameId-"+id).html();
    productName = productName.replace("&amp;", "||");
    
    if(value != -1)
    {
    removeChildren("attributeList-"+id, name, numChildren);
    var jpg = $("#imagename-"+id).val();
    productCount["options-"+id] = name+1;
    updateValues("values-"+id, productCount["options-"+id],value);
    $.post("/requests/getNextAttribute.php", {attributes: attributes, count: (productCount["options-"+id]-1), product: productName, image: jpg, values: $("#values-"+id).val()},
        function(data)
        {
            //alert(data);
            var newValues = data.split("|-");
            if(newValues[1] == '')
            {
                var attributes = newValues[0].split(",");
                var attributeName = attributes[productCount["options-"+id]];
                var values =  newValues[2].split(',');
                var options = "";
                for(i = 0; i < values.length; i++)
                {
                    options += "<option value='"+values[i]+"'>"+values[i]+"</option>\n";
                }
                var newHtml = "<div class='option' title='title-"+productCount["options-"+id]+"' >";
                newHtml += attributeName+": <Br /><select name='"+attributeName+"' class='ProductAttributesSelect' onchange='getNextAttribute(\"itemRow-"+id+"\","+productCount["options-"+id]+",this.value)'>";
                newHtml += "<option value='-1'>Select</option>";
                newHtml += options
                newHtml += "</select>";
                newHtml += "</div>";
                newHtml += needBr("options-"+id,productCount["options-"+id]);
                //.html(currentHtml+newHtml);
                $(newHtml).appendTo($("#attributeList-"+id));
                $("#cart-"+id).html('<img src="images/button_select_options.png" /><br>');
                $("#sId-"+id).val('');
            }
            else
            {
                removeChildren("attributeList-"+id, name, numChildren)
                $("#cart-"+id).html('QTY:<input size="3" maxlength="3" type="text" value="1" id="qty-cart-'+id+'" style="margin-bottom:5px"/><Br />'+newValues[3]+'<br><a href="javascript:void(0);" onclick="addToCart(\'itemRow-'+id+'\')"><img src="images/addToCart.png" border="0"/></a><br>');
                $("#sId-"+id).val(newValues[1]);
                $("#descSid-"+id).html("SID #: " + newValues[1]);
            }

            alignLeftBar();
        });
    }
}

function needBr(optionId,idNumber)
{
	var numChildren = $("#"+optionId+" > div").size();
	if(numChildren % 2 == 0)
		return '<br style="clear: both;" title="title-'+idNumber+'">';
	else
		return '';
}

function removeChildren(objectId, childName, numChildren)
{
    for(i = childName+1; i <= numChildren; i++)
    {

        $("#"+objectId+" > [title = title-"+i+"]").remove();
        //$("#"+objectId+" > br[title = title-"+i+"]").remove();
    }
}

function updateValues(objectId, count, value)
{
    var values = $("#"+objectId).val();
    values = values.split(",");
    var newVals = '';
    for(i = 0; i < count; i++)
    {
        if(i == (count - 1) && value != '')
            newVals += value + ",";
        else
            newVals += values[i] + ",";
    }
    $("#"+objectId).val(newVals);
}

function addValue(objectId, newValue)
{
    var current = $("#"+objectId).val();
    $("#"+objectId).val(current+newValue+",");
}

function addToCart(rowId)
{
    var id = rowId.split("-");
    id = id[1];
    
    var qty = $("#qty-cart-"+id).val();
    if(qty > 0)
    {
        var price = $("#priceId-"+id).val();
        var productName = $("#nameId-"+id).html();
        productName = productName.replace("&amp;", "||");
        var sid = $("#sId-"+id).val();
        $.post("/requests/addToCart.php", {productName:productName, sid:sid, qty:qty, price:price},
            function(data)
            {
                addMessage(productName + "<br /> was added to your cart");
                removeMessage();
                var cartSize = $("#cartSize").html();
                if(data == 0)
                    $("#cartSize").html((cartSize * 1) + 1);
            });
    }
    else
    {
        addMessage("Quantity must be greater than 0");
        removeMessage()
    }
}

function updateCart()
{
    var numBoxes = $(".orderSummary > div").size() - 3;
    var json = "";
    var boxName = "";
    var boxValue = "";
    for(i = 0; i <= numBoxes; i++)
    {
        boxName = $("#qty-"+i+" > input").attr("name");
        boxValue = $("#qty-"+i+" > input").val();

        if(isNaN(boxValue))
            boxValue = 0;
        
        if(i == numBoxes)
            json += boxName + "=" + boxValue;
        else
            json += boxName + "=" + boxValue + "&";

        if(boxValue <= 0)
            $("#row-"+i).remove();
    }
    $.ajax({
      type: "POST",
      url: "/requests/updateCart.php",
      data: json,
      success: function(data)
      {
            addMessage("Cart has been updated");
            removeMessage();
      }
    });
}

function addExistingClient()
{
    $("#existingClient").removeClass("hidden");
    $("#existingClient").addClass("visible");
}

function removeExistingClient()
{
    $("#existingClient").removeClass("visible");
    $("#existingClient").addClass("hidden");
}


function addMessage(message)
{
    $(".has-javascript").show();
    $(".has-javascript div").html(message);
    //$(".has-javascript span").css("", "/img/bg.jpg");
}

function removeMessage()
{
    $(".has-javascript").delay(2000).fadeOut(2000, function () {
            //
    });
}

function copyFields()
{
    if(copyInfoCount % 2 == 0)
    {
        for(var i = 0; i < formFields.length; i++)
        {
            $("#ShipTo"+formFields[i]).val($("#BillTo"+formFields[i]).val());
        }
    }
    copyInfoCount++;
    //$("#ShipToName").val($("#BillToName").val());
}

function validateRequestForm()
{
    var msg = '';
    for(var i = 0; i < requiredFormFields.length; i++)
    {
        shipVal = $("#ShipTo"+requiredFormFields[i]).val();
        billVal = $("#BillTo"+requiredFormFields[i]).val();
        emailVal = $("#ClientEmail").val();

        if($.trim(shipVal).length == 0)
        {
            msg = "Please fill in all required fields *.";
            $("#ShipTo"+requiredFormFields[i]).addClass("formError");
        }
        else
            $("#ShipTo"+requiredFormFields[i]).removeClass("formError");

        if($.trim(billVal).length == 0)
        {
            msg = "Please fill in all required fields *.";
            $("#BillTo"+requiredFormFields[i]).addClass("formError");
        }
        else
            $("#BillTo"+requiredFormFields[i]).removeClass("formError");
    }

    if($.trim(emailVal).length == 0 || !validateEmail(emailVal))
    {
        msg = "Please fill in all required fields *.";
        $("#ClientEmail").addClass("formError");
    }
    else
        $("#ClientEmail").removeClass("formError");

    if(msg.length == 0)
        return true;
    else
    {
        $("#errors").html(msg);
        alignLeftBar();
        //addMessage(msg);
        //removeMessage();
        return false;
    }
}


function validateContactForm()
{
    var msg = '';

    var phoneVal = $("#phone").val();
    var emailVal = $("#email").val();

    if($.trim(phoneVal).length == 0)
    {
        msg = "Please fill in all required fields *.";
        $("#phone").addClass("formError");
    }
    else
        $("#phone").removeClass("formError");

    if($.trim(emailVal).length == 0 || !validateEmail(emailVal))
    {
        msg = "Please fill in all required fields *.";
        $("#email").addClass("formError");
    }
    else
        $("#email").removeClass("formError");

    if(msg.length == 0)
        return true;
    else
    {
        $("#errors").html(msg);
        alignLeftBar();
        return false;
    }
}

function validateEmail(id)
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
return emailPattern.test(id);

}

function getCustomerInfo(value)
{
    $.post("/requests/getCustomerInfo.php", {customerNumber:value},
        function(data)
        {
            var dataArray = data.split("|");
            for(i = 1; i < dataArray.length; i++)
            {
                $("#BillTo"+formFields[i-1]).val(dataArray[i])

                if(i == (dataArray.length - 1))
                    $("#ClientEmail").val(dataArray[i]);
            }


        });
}

$(document).ready(function() {
    
     
});
