﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

$jq.ajaxSetup({
    type: "POST",
    cache: false,
    error: function(request) {
        //code to display message to user
    }
});


// validate that entry in all numeric text boxes is a number
$jq(document).ready(function() {
	$jq(".numerictextbox").live('keydown', function(event) {
		// Allow only backspace and delete
		if (event.keyCode == 46 || event.keyCode == 8) {
			// let it happen, don't do anything 
		}
		else {
			// Ensure that it is a number and stop the keypress
			if (event.keyCode < 48 || event.keyCode > 57 && event.keyCode < 96 || event.keyCode > 105) {
				event.preventDefault();
			}
		}
	});

	$jq('.paginator a').click(function() {
	    $jq('#page').val($jq(this).attr('page'));
	});
});

// validate that text entry field is numeric
function IsNumeric(input) {
	return (input - 0) == input && input.length > 0;
}

function addToCart(productId, quantity, callbackFunction) {
	if (!IsNumeric(quantity))
		quantity = 1;
	var test = '#qty' + productId;
	$jq('#qty' + productId).val('');
	$jq.ajax({
	    url: "/ProductCatalog/AddToCart/" + productId + "/" + quantity,
	    type: "Post",
	    data: "",
	    contentType: "application/json; charset=utf-8",
	    async: true,
	    cache: false,
	    dataType: "json",
	    success: function (data) {
        //  determine the kind of mini/microcart.  Pass on the result of the add to cart including the remaining inventory.
	        loadMiniCart(true, data.CartType);
	        if (callbackFunction)
	            callbackFunction(data.UpdateSuccess, data.NumberLeft, data.ProductId);
	    },
	    error: function (data) {
	        alert("Unhandled Error Occured");
	    }
	});
}


function loadMiniCart(popupMiniCart, data) {
    var cartUrl = "/MicroCart/false";
    if (data == "micro") {
        cartUrl = "/MicroCart/true";
    }
    $jq.ajax({
        url: cartUrl,
        async: true,
        cache: false,
        success: function(data) {
        $jq('#minicart').html(data);
        if (popupMiniCart)
                mcAddItem(data);
        },
        error: function() {
            alert("Unhandled Error");
        }
    });
}

function updateProductListData(productid, numLeft) {
    if (productid.length > 0) {
        if (numLeft == 0) {
            $jq('#addToCart' + productid).attr('style', 'display: none;');
            $jq('#ViewDetails' + productid).removeAttr("style");
            $jq('#ViewDetails' + productid).addClass("btn-addcart btn btnStyleA");
            if ($jq('#productqty' + productid)) {
                $jq('#productqty' + productid).attr('style', 'display: none;');
            }
            if ($jq('#qty' + productid)) {
                $jq('#qty' + productid).attr('style', 'display: none;');
            }
        }
        else if (numLeft != 0) {
                $jq('#addToCart' + productid).addClass("btn-addcart btn btnStyleA");
                $jq('#addToCart' + productid).removeAttr("style");
                $jq('#ViewDetails' + productid).attr('style', 'visibility: hidden;');
                if ($jq('#productqty' + productid)) {
                    $jq('#productqty' + productid).removeAttr('style');
                }
        }
    }
}

function addToCartCrossSell(showSuccess, numLeft, productid) {
    if (showSuccess == true) {
        var showConfirmation = $jq('#ShowAddToCartConfirmationDialog').val();
        if (showConfirmation.toLowerCase() == 'true') {
            $jq('#AddToCartPopup-link').click();
        }
    }
    else {
        $jq('#AddToCartNoInventory-Link').click();
    }
    updateProductListData(productid, numLeft);
}

function getProductsToAdd() {
	var items = new Array();
	$jq('.productQty').each(function() {
		if ($jq(this).val().length > 0) {
			var item = {};
			var productId = $jq(this).attr('productId');
			item.ProductId = productId;
			item.Color = $jq('#productColor[productid="' + productId + '"]').val();
			item.Size = $jq('#size-list[productid="' + productId + '"]').val();
			item.Quantity = $jq(this).val();
			items.push(item);
			$jq(this).val("");
		}
	});
	if (items.length == 0) {
		$jq('.productQty').each(function() {
			var item = {};
			var productId = $jq(this).attr('productId');
			item.ProductId = productId;
			item.Color = $jq('#productColor[productid="' + productId + '"]').val();
			item.Size = $jq('#size-list[productid="' + productId + '"]').val();
			item.Quantity = "1";
			items.push(item);
		});
	}
	return JSON.stringify(items);
}

function addAllToCart(jsonString, callbackFunction) {
	$jq.ajax({
		url: "/ProductCatalog/AddAllToCart?jsonString=" + jsonString,
		type: "Post",
		data: "",
		contentType: "application/json; charset=utf-8",
		async: true,
		cache: false,
		dataType: "json",
		success: function (data) {
		    loadMiniCart(true, data.CartType);
		    if (callbackFunction)
		        callbackFunction(data);
		},
		error: function(data) {
			alert("Unhandled Error Occured");
		}
	});
}

function saveWishList(wishListId, jsonString, callbackFunction) {
	$jq.ajax({
		url: "/WishList/SaveWishList/" + wishListId + "?jsonString=" + jsonString,
		type: "Post",
		data: "",
		contentType: "application/json; charset=utf-8",
		async: true,
		cache: false,
		dataType: "json",
		success: function(data) {
			if (callbackFunction)
				callbackFunction(data);
		},
		error: function(data) {
			alert("Unhandled Error Occured");
		}
	});
}


function removeFromWishList(wishListId, wishListProductId, callbackFunction) {
	$jq.ajax({
		url: "/WishList/RemoveWishListProduct/" + wishListId + "/" + wishListProductId,
		type: "Post",
		data: "",
		contentType: "application/json; charset=utf-8",
		async: true,
		cache: false,
		dataType: "json",
		success: function(data) {
			if (callbackFunction)
				callbackFunction(data);
		},
		error: function(data) {
			alert("Unhandled Error Occured");
		}
	});
}

function removeWishList(wishListId, callbackFunction) {
	$jq.ajax({
		url: "/WishList/Remove/" + wishListId,
		type: "Post",
		data: "",
		contentType: "application/json; charset=utf-8",
		async: true,
		cache: false,
		dataType: "json",
		success: function(data) {
			if (callbackFunction)
				callbackFunction(data);
		},
		error: function(data) {
			alert("Unhandled Error Occured");
		}
	});
}

function addProductToWishList(productId, quantity, callbackFunction) {
	if (!IsNumeric(quantity))
		quantity = 1;

	$jq.ajax({
	    url: "/WishList/AddWishListProduct/" + productId + "/" + quantity,
        type: "Post",
        data: "",
        contentType: "application/json; charset=utf-8",
        async: true,
        cache: false,
        dataType: "json",
        success: function (data) {
            if (callbackFunction)
                callbackFunction(data);
        },
        error: function (data) {
            alert("Unhandled Error Occured");
        }
    });

}

function addToWishList(wishListName, productId, quantity, callbackFunction) {
	if (!IsNumeric(quantity))
		quantity = 1;

	$jq.ajax({
		url: "/WishList/AddProductToWishlist/" + wishListName + "/" + productId + "/" + quantity,
		type: "Post",
		data: "",
		contentType: "application/json; charset=utf-8",
		async: true,
		cache: false,
		dataType: "json",
		success: function(data) {
            //wtf was this?
		},
		error: function(data) {
			alert("Unhandled Error Occured");
		}
	});
}


function addListProductToWishList(wishListName, productId, quantity, callbackFunction) {

	if (!IsNumeric(quantity))
		quantity = 1;

	$jq.ajax({
		url: "/WishList/AddListProductToWishList/" + wishListName + "/" + productId + "/" + quantity,
		type: "Post",
		data: "",
		contentType: "application/json; charset=utf-8",
		async: true,
		cache: false,
		dataType: "json",
		success: function(data) {
			if (callbackFunction) {
				callbackFunction(data);
			}
		},
		error: function(data) {
			alert("Unhandled Error Occured");
		}
	});
}

function quickOrderFindProduct(productNum, quantity, rowDOM, callbackFunction) {
	if (quantity.length == 0)
		quantity = 1;

	$jq.ajax({
		url: "/QuickOrder/FindProduct/" + productNum + "/" + quantity,
		type: "Post",
		data: "",
		contentType: "application/json; charset=utf-8",
		async: true,
		cache: false,
		dataType: "json",
		success: function(data) {
			if (callbackFunction)
				callbackFunction(data, rowDOM);
		},
		error: function(data) {
			alert("Unhandled Error Occured");
		}
	});
}

function submitOnEnter(textBox, e) {

	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
		textBox.form.submit();
		return false;
	}
	else
		return true;
}

function loadWishListGrid(wishListId) {
	$jq.ajax({
		url: '/WishList/WishListGrid/' + wishListId,
		async: true,
		cache: false,
		success: function(data) {
			$jq('#wishlistgrid').html(data);
		},
		error: function(data) {
			alert("Unhandled Error Occured");
		}
	});
}

function loadOrderHistoryGrid(pageSize, page, sort, jsonString) {
	if (jsonString != null) {
		$jq.ajax({
			url: '/Account/OrderHistoryGrid/' + pageSize + '/' + page + '/' + sort + '?jsonString=' + jsonString,
			async: true,
			cache: false,
			success: function(data) {
				$jq('#orderhistorygrid').html(data);
			},
            error: function (request, error) {
                if (request.status == 400) {
                    alert(request.responseText);
                }
                else {
                    alert("Unhandled Error Occurred!");
                }
            }
        });
	}
	else {
	    $jq.ajax({
	        url: '/Account/OrderHistoryGrid/' + pageSize + '/' + page + '/' + sort,
	        async: true,
	        cache: false,
	        success: function (data) {
	            $jq('#orderhistorygrid').html(data);
	        },
	        error: function (request, error) {
	            if (request.status == 400) {
	                alert(request.responseText);
	            }
	            else {
	                alert("Unhandled Error Occurred!");
	            }
	        }
	    });
	}

}

function loadInvoiceHistoryGrid(pageSize, page, sort, jsonString) {
	if (jsonString != null) {
		$jq.ajax({
			url: '/Account/InvoiceHistoryGrid/' + pageSize + '/' + page + '/' + sort + '?jsonString=' + jsonString,
			async: true,
			cache: false,
			success: function(data) {
				$jq('#invoicehistorygrid').html(data);
			},
            error: function (request, error) {
                if (request.status == 400) {
                    alert(request.responseText);
                }
                else {
                    alert("Unhandled Error Occurred!");
                }
            }
        });
	}
	else {
		$jq.ajax({
			url: '/Account/InvoiceHistoryGrid/' + pageSize + '/' + page + '/' + sort,
			async: true,
			cache: false,
			success: function(data) {
				$jq('#invoicehistorygrid').html(data);
			},
            error: function (request, error) {
                if (request.status == 400) {
                    alert(request.responseText);
                }
                else {
                    alert("Unhandled Error Occurred!");
                }
            }
        });
	}

}

function changePage(page) {
	var form = document.getElementById('paramForm');
	form.page.value = page;
	form.submit();
}

function changePageSize(obj) {
	var form = document.getElementById('paramForm');
	form.page.value = "1";
	form.pageSize.value = obj.options[obj.selectedIndex].value;
	form.submit();
}

function changeSortBy(obj) {
	var form = document.getElementById('paramForm');
	form.page.value = "1";
	form.sortby.value = obj.options[obj.selectedIndex].value;
	form.submit();
}

function changeFilter(obj) {
	var form = document.getElementById('paramForm');
	var selectedValue = obj.options[obj.selectedIndex].value;
	if (selectedValue == "") {
		for (var i = 0; i < obj.options.length; i++) {
			var val = obj.options[i].value.replace(/^\s+|\s+$/g, "");
			if (val.length == 0) {
				continue;
			}
			if (form.filters.value.indexOf(val) >= 0) {
				form.filters.value = form.filters.value.replace(val, "");
			}
		}
		var valueArray = form.filters.value.split(',');
		var newValue = "";
		for (var j = 0; j < valueArray.length; j++) {
			if (valueArray[j].replace(/^\s+|\s+$/g, "").length != 0) {
				newValue += valueArray[j];
			}
		}
	}
	else {
		form.filters.value = form.filters.value.length == 0 ? selectedValue : form.filters.value + ',' + selectedValue;
	}
	form.page.value = "1";
	form.submit();
}

function changeCategory(id) {
	var form = document.getElementById('paramForm');
	form.page.value = "1";
	form.categoryId.value = id;
	form.submit();
}


function clearFilters() {
	var form = document.getElementById('paramForm');
	form.filters.value = "";
	form.page.value = "1";
	form.submit();
}
function isValidEmail(emailStr) {
	var emailRegEx = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return emailRegEx.test(emailStr);
}
function isValidZip(zipStr) {
	var zipRegEx = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
	return zipRegEx.test(zipStr);
}
function searchSumbitOnClick() {
	var theForm = document.forms["searchform"];
	var isValid = validateSearch();
	if (isValid == true)
		theForm.submit();
	else
		theForm.criteria.focus();
}
function validateSearch() {
	var theForm = document.forms["searchform"];
	var criteria = theForm.criteria.value.replace(/^\s+|\s+$/g, "");
	return criteria.length != 0 && criteria.toLowerCase() != 'search';
}

function subscribeOnClick() {
	var theForm = document.forms["subscribeForm"];
	var email = theForm.subscribe.value.replace(/^\s+|\s+$/g, "");
	var isValid = isValidEmail(email);
	if (isValid == true) {
	    var postData = { emailAddress: email };
		$jq.ajax({
			url: "/Account/SubscribeToNewsletter/" + email,
			type: "Post",
			data: JSON.stringify(postData),
			contentType: "application/json; charset=utf-8",
			async: true,
			cache: false,
			dataType: "json",
			success: function(data) {
				if (data.URL)
					window.location = data.URL;
				else {
					if (data == 'Already Subscribed') {
	                    $jq("#subscription_already-link").click();
					    
						theForm.email.value = "";

					}
					else if (data == 'Successfully Subscribed') {
	                    $jq("#subscription_done-link").click();
						theForm.email.value = "";
					}
					else {
	                    $jq("#subscription_done-link").click();
						theForm.email.value = "";
					}
				}
			},
			error: function(data) {
				$jq("#ajax_error-link").click();
}
		});
	}
	else {
	    $jq("#subscription_invalidemail-link").click();
	}
}
     
