//////////////////////////////////////////
// load shipping rates via jquery-ajax. //
//////////////////////////////////////////


function loadshipping(){

	// disabled continue button
	$('#CheckOutButton').attr("disabled", true);

	// display loading image
	$('#ShippingQuoteArea').html("<center><font size='1'><b>calculating shipping rate</b></font><br /><img src='/images/ajax-loader.gif' /></center>");
	$.post(
		"/includes/AjaxFunctions.php",
		{
			action: "ShippingRates"
		},
		function(data) {
			$("#ShippingQuoteArea").html(data);
			$('#CheckOutButton').attr("disabled", false);
		},
		"html"
	);

}



function CheckShippingSpecs(){
	var ShippingCheck = false;
	var cnt = 4;
	for(var i=1; i<cnt; i++){

		if($("#LengthValue_" + i).val() > 0){
			ShippingCheck = true;
		}
	/*
		LengthValue_1
		WidthValue_1
		HeightValue_1
		Weight_1
	*/
	}
	if(ShippingCheck == false){
		$("#POSActiveBypass").attr('checked', 'checked');
		alert("Shipping Details have not been set.\nPOS Activity Bypass has been enabled");
	}
}


//////////////////////////////////////////
// Validate In-Store Clearance Products //
//////////////////////////////////////////


function SetQty(){

	var ConditionDrop = $('#Condition').val();
	var ProductQty	  = $('#Qty');


	if(ConditionDrop == "New" || ConditionDrop == "Demo"){

		ProductQty.val(0);
		ProductQty.attr('disabled', false);

	} else if(ConditionDrop == "Used"){

		ProductQty.val(1);
		ProductQty.attr('disabled', true);

	}

}

function Trim(str){
	return str.replace(/^\s+|\s+$/g, '') ;
}

function ValidateStoreProducts(){

	var ConditionDrop = $('#Condition').val();
	var ProductSku	  = $('#Sku').val();
	var ProductSerial = $('#Serial').val();
	var ProductQty	  = $('#Qty');
	var ProductModel  = $('#Model');

	if(ConditionDrop == "New" || ConditionDrop == "Demo" && ProductSku.length > 0){

		ProductQty.val(0);
		ProductQty.attr('disabled', false);


		$.post(
			"/manager/AjaxClearance.php",
			{
				action: "new",
				ProductSku: ProductSku
			},
			function(data) {
				if(Trim(data) == 0){
					alert("Error: Invalid Sku");
				} else {
					ProductModel.val(data);
				}
			},
			"html"
		);


	} else if(ConditionDrop == "Used" && ProductSku.length > 0 && ProductSerial.length > 0){

		ProductQty.val(1);
		ProductQty.attr('disabled', true);


		$.post(
			"/manager/AjaxClearance.php",
			{
				action: "used",
				ProductSku: ProductSku,
				ProductSerial: ProductSerial
			},
			function(data) {
				if(Trim(data) == 0){
					alert("Error: Invalid 'Sku' or 'Serial Number' was entered.");
				} else {
					ProductModel.val(data);
				}
			},
			"html"
		);


	}

}


//////////////////////////////////////////
// auto complete city & prov by postal  //
//////////////////////////////////////////

function loadCompleteAddress(){

	var HomeCity = $('#HomeCity');
	var ProvincesID = $('#ProvincesID');
	var PostalCode = $('#PostalCode');

	if(HomeCity.val().length == 0 && ProvincesID.val() == 0){

		$.post(
			"/includes/AjaxFunctions.php",
			{
				action: "AddressLookup",
				zip: PostalCode.val()
			},
			function(data) {
					//alert(data);
				var ReturnData = data.split("|");
				HomeCity.val(ReturnData[0]);
				//alert(ReturnData[1]);
				ProvincesID.val(ReturnData[1]);
			},
			"html"
		);
	}
}

function loadStockAvailability(){

	// product id
	var ProductsID = document.getElementById("ProductsIDTemp").value;

	var BrandID = document.getElementById("BrandIDTemp").value;


	//alert('Product ID: ' + ProductsID + ' Brand ID: ' + BrandID);

	// display loading image
	$("#StockNotice").html("<img src='/images/ajax-loader.gif' />");

	$.post(
		"/includes/AjaxFunctions.php",
		{
			action: "ProductAvailability",
			ProductsID: ProductsID,
			BrandID: BrandID
		},
		function(data) {
			$(".ProductStockAvail").html(data);
		},
		"html"
	);
}

$(document).ready(function() {

	//Select all anchor tag with rel set to tooltip
	$('a[rel=tooltip]').mouseover(function(e) {
		
		//Grab the title attribute's value and assign it to a variable
		var tip = $(this).attr('title');	
		
		//Remove the title attribute's to avoid the native tooltip from the browser
		$(this).attr('title','');
		
		//Append the tooltip template and its value
		$(this).append('<div id="tooltip"><div class="tipHeader"></div><div class="tipBody">' + tip + '</div><div class="tipFooter"></div></div>');		
				
		//Show the tooltip with faceIn effect
		$('#tooltip').fadeIn('500');
		$('#tooltip').fadeTo('10',0.9);
		
	}).mousemove(function(e) {
	
		//Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
		$('#tooltip').css('top', e.pageY - 155 );
		$('#tooltip').css('left', e.pageX + 20 );
		
	}).mouseout(function() {
	
		//Put back the title attribute's value
		$(this).attr('title',$('.tipBody').html());
	
		//Remove the appended tooltip template
		$(this).children('div#tooltip').remove();
		
	});

});

///////////////////////////
// Ajax Functions
///////////////////////////

function GetXmlHttpObject() {
	var xmlHttp = null;
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		xmlHttp = new XMLHttpRequest();
		if (xmlHttp.overrideMimeType) xmlHttp.overrideMimeType('text/xml');
	} else if (window.ActiveXObject) { // IE
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert ("Browser does not support HTTP Request")
				return false;
			}
		}
	}
	return xmlHttp;
}

// send google lat/lng request
function LoadGooleMap(){

	// display loading image
	document.getElementById("MapArea").innerHTML = "<img src='/images/loading.gif' />";

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;
	var SteetAddress = document.getElementById("SteetAddress").value;
	var PostalCode = document.getElementById("PostalCode").value;
	var City = document.getElementById("City").value;
	var Prov = document.getElementById("ProvincesID").value;

	var url="/admin/Location_Search.php?";
	url=url+"SteetAddress=" + SteetAddress;
	url=url+"&PostalCode=" + PostalCode;
	url=url+"&City=" + City;
	url=url+"&Prov=" + Prov;

	xmlHttp.onreadystatechange=function() { DisplayMap( xmlHttp ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

// display google map query result
function DisplayMap( xmlHttp ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var LatLng = xmlHttp.responseText.split("|");
		document.getElementById("MapLat").value = LatLng[0];
		document.getElementById("MapLng").value = LatLng[1];
		load();
	}
}




///////////////////
// WishList Ajax //
///////////////////

function AddRecipient(){

	var strName  = document.getElementById("Name");
	var strEmail = document.getElementById("Email");

	var Errmsg = "";
    if(strName.value == "")					   Errmsg += ("You must enter a Name to continue\n");
    if(ValidateEmail(strEmail.value) == false) Errmsg += ("You must enter a valid Email Address to continue\n");

	if(!Errmsg==""){
		alert('Some errors were found:\n_______________________\n' + Errmsg);
		return false;
	} else {

		var xmlHttp;
		xmlHttp=GetXmlHttpObject();
		if (!xmlHttp) return false;
		var url="/includes/AjaxFunctions.php?action=AddWishListRecipiant&Name=" + strName.value + "&Email=" + strEmail.value;
		xmlHttp.onreadystatechange=function() { UpdateWishList( xmlHttp ); };
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);

		// clear fields
		strName.value = "";
		strEmail.value= "";

		// display list
		DisplayWishList();

	}
}

function UpdateWishList( xmlHttp ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		if(response == 1){
			alert("response: " + response);
			//document.getElementById("WishListRecipiantArea").innerHTML = response;
		}
	}
}

function DisplayWishList(){
	$.ajax({
	  url: '/includes/AjaxFunctions.php?action=WishListRecipiantsList',
	  success: function(data) {
		$('#WishListRecipiantArea').html(data);
	  }
	});
}

function RemoveRecipient(id){
	$.ajax({
	  url: '/includes/AjaxFunctions.php?action=RemoveWishListRecipiant&id=' + id
	});

	  DisplayWishList();
}



//////////////////////
// order incomplete //
//////////////////////

function AdminOrderComplete(numOrderID){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;
	var url="/admin/AdminOrderComplete.php?OrderID=" + numOrderID;
	xmlHttp.onreadystatechange=function() { UpdateIncomplete( xmlHttp, numOrderID ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function UpdateIncomplete( xmlHttp, numOrderID ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		if(response == 0){
			ImageChange = new Image();
			ImageChange.src = "/admin/images/stars/star_off.jpg";
			document.getElementById('IncompleteImage_' + numOrderID ).src = ImageChange.src;
		} else {
			ImageChange = new Image();
			ImageChange.src = "/admin/images/stars/star_on.jpg";
			document.getElementById('IncompleteImage_' + numOrderID ).src = ImageChange.src;
		}
	}
}

//////////////////////
// Feature Products //
//////////////////////

function AdminFeaturedProducts(numProductID){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;
	var url="/admin/AdminFeatured.php?ProductID=" + numProductID;
	xmlHttp.onreadystatechange=function() { UpdateFeaturedProducts( xmlHttp, numProductID ); };
	//xmlHttp.onreadystatechange=function() { debug( xmlHttp ); };

	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function UpdateFeaturedProducts( xmlHttp, numProductID ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		if(response == 0){
			ImageChange = new Image();
			ImageChange.src = "/admin/images/stars/star_off.jpg";
			document.getElementById('FeaturedImage_' + numProductID ).src = ImageChange.src;
		} else {
			ImageChange = new Image();
			ImageChange.src = "/admin/images/stars/star_on.jpg";
			document.getElementById('FeaturedImage_' + numProductID ).src = ImageChange.src;
		}
	}
}

/////////////////////
// Banner Rotation //
/////////////////////


function BannerRotation(numHomePageBannerRotationID){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;
	var url="/admin/BannersEnabled.php?HomePageBannerRotationID=" + numHomePageBannerRotationID;
	xmlHttp.onreadystatechange=function() { UpdateBannerRotation( xmlHttp, numHomePageBannerRotationID ); };
	//xmlHttp.onreadystatechange=function() { debug( xmlHttp ); };

	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function UpdateBannerRotation( xmlHttp, numHomePageBannerRotationID ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		if(response == 0){
			ImageChange = new Image();
			ImageChange.src = "/admin/images/stars/star_off.jpg";
			document.getElementById('Status_' + numHomePageBannerRotationID ).src = ImageChange.src;
		} else {
			ImageChange = new Image();
			ImageChange.src = "/admin/images/stars/star_on.jpg";
			document.getElementById('Status_' + numHomePageBannerRotationID ).src = ImageChange.src;
		}
	}
}


///////////////////
// Avtive Events //
///////////////////

function ActiveEvents(id){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;
	var url="/admin/ActiveEvents.php?id=" + id;
	xmlHttp.onreadystatechange=function() { UpdateActiveEvents( xmlHttp, id ); };
	//xmlHttp.onreadystatechange=function() { debug( xmlHttp ); };

	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function UpdateActiveEvents( xmlHttp, id ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		if(response == 0){
			ImageChange = new Image();
			ImageChange.src = "/admin/images/stars/star_off.jpg";
			document.getElementById('Status_' + id ).src = ImageChange.src;
		} else {
			ImageChange = new Image();
			ImageChange.src = "/admin/images/stars/star_on.jpg";
			document.getElementById('Status_' + id ).src = ImageChange.src;
		}
	}
}

///////////////////////////////////
// Product Accessories Functions //
///////////////////////////////////

function ManageAdminSections(numAdminID,PageID,strAction){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/AdminSections.php?action=" + strAction + "&";
	url=url+"AdminID=" + numAdminID;
	url=url+"&PageID=" + PageID;
	//xmlHttp.onreadystatechange=function() { debug( xmlHttp ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function ManageBrandsProvinces(BrandsID,ProvincesID,strAction){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/BrandsProvinces.php?action=" + strAction + "&";
	url=url+"BrandsID=" + BrandsID;
	url=url+"&ProvincesID=" + ProvincesID;
	//xmlHttp.onreadystatechange=function() { debug( xmlHttp ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function ManageAdminBrands(numAdminID,BrandsID,strAction){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/AdminBrands.php?action=" + strAction + "&";
	url=url+"AdminID=" + numAdminID;
	url=url+"&BrandsID=" + BrandsID;
	//xmlHttp.onreadystatechange=function() { debug( xmlHttp ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function ManageAccessory(numProductID,numAccessoryID,strAction){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/ProductAccessories.php?action=" + strAction + "&";
	url=url+"ProductID=" + numProductID;
	url=url+"&AccessoryID=" + numAccessoryID;
	//xmlHttp.onreadystatechange=function() { debug( xmlHttp ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function ManageDepartments(numProductID,DepartmentsID,strAction){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/ProductDepartments.php?action=" + strAction + "&";
	url=url+"ProductID=" + numProductID;
	url=url+"&DepartmentsID=" + DepartmentsID;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function ManageRelated(numProductID,RelatedID,strAction){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/ProductRelated.php?action=" + strAction + "&";
	url=url+"ProductID=" + numProductID;
	url=url+"&RelatedID=" + RelatedID;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function ManageSaleProducts(numProductID,strAction,ProvincesID){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/ProductsOnSale.php?action=" + strAction + "&ProductID=" + numProductID + "&ProvincesID=" + ProvincesID;
	//xmlHttp.onreadystatechange=function() { debug( xmlHttp ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

// for use after checkout
function ResetSession(){
	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;
	xmlHttp.open("GET","/includes/reset_session.php",true);
	xmlHttp.send(null);
}

// display google map query result
function debug( xmlHttp ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		alert(response);
	}
}

// for use after checkout
function AdminCanadaPostShippingRate(form, ProductsID){
	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/cplookup.php?";
	url=url+"ProductsID=" + ProductsID
	xmlHttp.onreadystatechange=function() { AdminCanadaPostShippingRateResult( xmlHttp ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);

}

function AdminCanadaPostShippingRateResult( xmlHttp ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		alert(response);
	}
}


// for use after checkout
function AdminPurolatorShippingRate(form, ProductsID){
	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;

	var url="/admin/plookup.php?";
	url=url+"ProductsID=" + ProductsID
	xmlHttp.onreadystatechange=function() { AdminPurolatorShippingRateResult( xmlHttp ); };
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);

}

function AdminPurolatorShippingRateResult( xmlHttp ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		alert(response);
	}
}


// Admin Products Accessories Quick Search
function AdminProductsQuickSearch(numProductsID){

	var xmlHttp;
	xmlHttp=GetXmlHttpObject();
	if (!xmlHttp) return false;
	xmlHttp.open("GET","/admin/AjaxProductsList.php?ProductsID=" + numProductsID,true);
	xmlHttp.onreadystatechange=function() { AdminProductsQuickSearchResult( xmlHttp ); };
	xmlHttp.send(null);

}


function AdminProductsQuickSearchFilter(numProductsID, strSeatchText){

	if(strSeatchText.length > 2){
		var xmlHttp;
		xmlHttp=GetXmlHttpObject();
		if (!xmlHttp) return false;
		xmlHttp.open("GET","/admin/AjaxProductsList.php?ProductsID=" + numProductsID + "&SeatchText=" + strSeatchText,true);
		xmlHttp.onreadystatechange=function() { AdminProductsQuickSearchResult( xmlHttp ); };
		xmlHttp.send(null);
	}
}

function AdminProductsQuickSearchResult( xmlHttp ){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		document.getElementById("AdminProductsQuickSearchArea").innerHTML = xmlHttp.responseText;
	}
}



///////////////////////////
// Site Form Validations //
///////////////////////////


function ValidateEmail(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
		return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
		return false;
	}
	if (str.indexOf(" ")!=-1){
		return false;
	}
	return true					
}

function CheckContactForm(form){

	var Errmsg = "";

    if(form.EmailName.value == "")						Errmsg += ("You must enter your Name to continue\n");
    if(ValidateEmail(form.EmailAddress.value) == false) Errmsg += ("You must enter a valid Email Address to continue\n");
    if(form.EmailMessage.value == "")					Errmsg += ("You must enter a Message to continue\n");
	if(form.Location.value == 0)						Errmsg += ("You must select your nearest store to continue");

	if(!Errmsg==""){
		alert('Some errors were found:\n_______________________\n' + Errmsg);
		return false;
	} else {
		return true;
	}
	return false;
}

function ValidateSearch(){
	var strSearch = document.getElementById("SearchTxt");
	if(strSearch.value == ""){
		alert("You must enter a search term to continue");
		return false;
	}
	return true;
}

function ValidateLoginForm(form){
	if(form.UserEmail.value == ""){
		alert("You must enter an your email address to continue");
		return false;
	}
	if(form.UserPass.value == ""){
		alert("You must enter your password to continue");
		return false;
	}
	return true;
}

function ValidatePassResetForm(form){
	if(form.UserPass.value == ""){
		alert("You must enter a new password to continue");
		return false;
	}
	if(form.ConfirmUserPass.value == ""){
		alert("You must confirm your new password to continue");
		return false;
	}
	if(form.UserPass.value !== form.ConfirmUserPass.value){
		alert("passwords to not match, please try again");
		// clear passwords
		form.ConfirmUserPass.value = ""
		form.UserPass.value = ""
		form.UserPass.focus();
		return false;
	}
	return true;
}

function ValidateAccountInfo(form){

	var Errmsg = "";

	if(form.FirstName.value == "")   Errmsg += ("You must enter your first name to continue\n");
	if(form.LastName.value == "")    Errmsg += ("You must enter your last name to continue\n");
	if(form.HomePhone.value == "")   Errmsg += ("You must enter your phone number to continue\n");
	if(form.HomeAddress.value == "") Errmsg += ("You must enter your home address to continue\n");
	if(form.HomeCity.value == "")	 Errmsg += ("You must enter your city to continue\n");
	if(form.PostalCode.value == "")  Errmsg += ("You must enter your postal code to continue\n");
	if(ValidateEmail(form.Email.value) == false) Errmsg += ("You must enter a valid email address to continue\n");
	if(form.Password.value !== form.ConfirmPassword.value) Errmsg += ("Your passwords do not match\n");
	if(form.agree.checked == false) Errmsg += ("You must agree to the Terms & Conditions to continue\n");
	if(form.ProvincesID.value == 0)  Errmsg += ("You must select a province to continue\n");

	if(!Errmsg==""){
		alert('Some errors were found:\n_______________________\n' + Errmsg);
		return false;
	} else {
		DisableButton(form.PasswordButton);
		return true;
	}
	return false;
}

function ValidateJoinUs(form){

	var Errmsg = "";
	if(form.name.value == "")		Errmsg += "Please enter your full name to continue\n";
	if(form.address.value == "")	Errmsg += "Please enter your address continue\n";
	if(form.city.value == "")		Errmsg += "Please enter your province continue\n";
	if(form.province.value == "")	Errmsg += "Please enter your full name to continue\n";
	if(form.phone.value == "")		Errmsg += "Please enter your phone number to continue\n";
	if(form.email.value == "")		Errmsg += "Please enter your email address to continue\n";
	if(form.instrument.value == "") Errmsg += "Please enter your instruments played to continue\n";
	if(form.experience.value == "") Errmsg += "Please enter your Previous and Current Work Experience to continue\n";
	if(form.full.value == "")		Errmsg += "Please enter your Interest in Full or Part Time Employment to continue\n";
	if(form.location.value == "")	Errmsg += "Please enter your Interest in Working at a Specific Location to continue\n";
	if(form.yourself.value == "")	Errmsg += "Please Tell Us About Yourself to continue\n";

	if(!Errmsg==""){
		alert('Some errors were found:\n_______________________\n' + Errmsg);
		return false;
	} else {
		return true;
	}
	return false;
}



function ValidateCheckOutForm(form){

	if(form.HomePhone.value == ""){
		alert("You must enter your phone number to continue");
		form.HomePhone.focus();
		return false;
	}

	if(form.HomeAddress.value == ""){
		alert("You must enter your home address to continue");
		form.HomeAddress.focus();
		return false;
	}

	if(form.HomeCity.value == ""){
		alert("You must enter your city to continue");
		form.HomeCity.focus();
		return false;
	}

	if(form.PostalCode.value == ""){
		alert("You must enter your postal code to continue");
		form.PostalCode.focus();
		return false;
	}

	if(!isValidPostalcode(form.PostalCode.value)){
		alert("You must enter a valid shipping postal code to continue");
		form.PostalCode.focus();
		return false;
	}

    var PaymentMethod = form.PaymentMethod;
    if(PaymentMethod[0].checked == true){

		if(form.NameOnCard.value == ""){
			alert("You must enter the name that appears on your credit card to continue");
			form.NameOnCard.focus();
			return false;
		}

		// CC Validation
		if(form.CardNumber.value == ""){
			alert("You must enter a valid credit card number to continue");
			form.CardNumber.focus();
			return false;
		}

		if(form.PIN.value == ""){
			alert("You must enter your credit card PIN number to continue");
			form.NameOnCard.focus();
			return false;
		}

	}
	return true;
}

// validate canadian postal code
function isValidPostalcode(postalcode) {
	if (postalcode.length == 6 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/) != -1) return true;
	else if (postalcode.length == 7 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z](-|\s)\d[a-zA-Z]\d$/) != -1) return true;
	else return false;
}


function ValidateMaillingListForm(form){

	var Errmsg = "";
	if(form.FirstName.value == "")	Errmsg += "Your First Name is required.\n";
	if(form.LastName.value == "")	Errmsg += "Your Last Name is required.\n";
	if(form.postal.value == "")		Errmsg += "Your Postal Code is required.\n";
	if(ValidateEmail(form.email.value) == false) Errmsg += "A valid email address is required to continue.\n";

	if(!Errmsg==""){
		alert('Some errors were found:\n_______________________\n' + Errmsg);
		return false;
	} else {
		return true;
	}
	return false;
}

function ValidateHelp(form){
    var err = '';
    if(form.FullName.value == '') err += "Your must fill in your full name to continue\n";
    if(ValidateEmail(form.Email.value) == false) err += "Your must fill in a valid email address to continue\n";
    if(form.Msg.value == '')	  err += "Please add a message explaining your issue";

    if(!err == ""){
        alert('Some errors were found:\n_______________________\n' + err );
        return false;
    } else {
        return true;
    }
}

function ValidatePostalCode(form){
	if(form.PostalCode.value == "" || form.PostalCode.value == "Postal Code"){
		alert("You must enter a valid postal code to continue");
		return false;
	}
	return true;
}

///////////////////
// JQuery Search //
///////////////////

// submit search on select
function SubmitSearchForm(){
	//if(document.SearchForm.SearchTxt.length > 0){
		document.SearchForm.submit();
	//}
}

$().ready(function() {
	$("#SearchTxt").autocomplete("/AjaxSearch.php", {
		width: 300,
		selectFirst: false
	}).result(SubmitSearchForm);
});


function HideDepartment(strTableName,strImageName){

	var myTableObj = document.getElementById(strTableName);
	myTableObj.style.display = (myTableObj.style.display == '') ? 'none' : '';

	ImageFlipClose = new Image();
	ImageFlipClose.src = "/images/minus.gif";
	ImageFlipOpen = new Image();
	ImageFlipOpen.src = "/images/plus.gif";

	var strImageOn = document.getElementById(strImageName);
	strImageOn.src = (strImageOn.src == ImageFlipClose.src) ? ImageFlipOpen.src : ImageFlipClose.src;
}

/////////////////////////////
// Recover Password JQuery //
/////////////////////////////

function RecoverPassword(){
	var strEmailAddress = document.getElementById("RecoverEmail");
	if(strEmailAddress.value == ""){
		alert("You must enter your email address to continue");
	} else {
		var xmlHttp;
		xmlHttp=GetXmlHttpObject();
		if (!xmlHttp) return false;
		var url="/AjaxRecoverPassword.php?Email=" + strEmailAddress.value;
		xmlHttp.onreadystatechange=function() { RecoverPasswordResult( xmlHttp ); };
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}
}

function RecoverPasswordResult( xmlHttp ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;
		if(response == 1){
			document.getElementById("RecoverPasswordDivArea").innerHTML = "<font size='2'>Your account has been found. Instructions on how to reset your password have been send to your email address.</font>";
		} else {
			alert("Account Not Found, Please try again.");
		}
	}
}


/////////////////////////
// Display Store Stock //
/////////////////////////

function GetInStoreStock(Sku, ProvinceID){
		var xmlHttp;
		xmlHttp=GetXmlHttpObject();
		if (!xmlHttp) return false;
		var url="/includes/AjaxGetInStoreStock.php?Sku=" + Sku + "&ProvinceID=" + ProvinceID;
		xmlHttp.onreadystatechange=function() { RecoverPasswordResult( xmlHttp ); };
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
}



////////////////////////////
// Add Product Sku Lookup //
////////////////////////////

function LookupSku(sku){
	if(sku!==""){
		var xmlHttp;
		xmlHttp=GetXmlHttpObject();
		if (!xmlHttp) return false;
		var url="SKUSearch.php?sku=" + sku;
		xmlHttp.onreadystatechange=function() { ReturnSku( xmlHttp ); };
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}
}

function ReturnSku( xmlHttp ) {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		var response = xmlHttp.responseText;

			//alert(response);

		if(response == 1){ // duplicate sku
			document.getElementById("SkuReturnMsg").innerHTML = "This SKU already exists in the system";
			document.getElementById("FormCheck").value = 1;
		} else if(response == 2){ // invalid sku
			document.getElementById("SkuReturnMsg").innerHTML = "This SKU is invalid";
			document.getElementById("FormCheck").value = 1;
		} else { // good sku, continue to load data

			var ProductDetails = response.split("|");

			document.getElementById("ProductModel").value = ProductDetails[0];
			document.getElementById("ProductName").value  = ProductDetails[1];
			document.getElementById("ProductPrice").value = ProductDetails[2];
			document.getElementById("SalePrice").value    = ProductDetails[3];
			document.getElementById("TeacherPrice").value = ProductDetails[4];

			document.getElementById("SkuReturnMsg").innerHTML = "New SKU";
			document.getElementById("FormCheck").value = 0;
		}
	}
}

function ProductFormCheck(){
	if(document.getElementById("FormCheck").value == 1){
		alert("This SKU already exists in the system, please check the sku and try again.");
		return false;
	}
	return true;
}

// Share on MySpace
function GetThis(T, C, U, L){
    var targetUrl = 'http://www.myspace.com/index.cfm?fuseaction=postto&' + 't=' + encodeURIComponent(T)
    + '&c=' + encodeURIComponent(C) + '&u=' + encodeURIComponent(U) + '&l=' + L;
    window.open(targetUrl);
}

/////////////////////////////////
// Convert Metric to Impearial //
/////////////////////////////////

function roundit(which){
    return Math.round(which*100)/100
}

function GetValue(strElement){
    return document.getElementById(strElement).value;
}

function DisplayResult(strElement,strValue){
    return document.getElementById(strElement).value = strValue;
}

function ConvertWeight(InputField,OutputField){
    var numWeight = GetValue(InputField);
    var numLBS = ( numWeight * 2.2 );
    DisplayResult(OutputField,' = ' + roundit(numLBS) + ' lbs');
}

function ConvertSize(InputField,OutputField){
    var numSize = GetValue(InputField);
    var numCM = ( numSize * 0.3937008 );
    DisplayResult(OutputField,' = ' + roundit(numCM) + ' inches');
}

/////////////////

function RelatedProductsJump(numProductID){
	if(numProductID > 0){
		location.href='/?page=products&ProductsID=' + numProductID;
	}
}

function popUp(URL,Width,Height) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=" + Width + ",height=" + Height + ",left = 790,top = 475');");
}

function changeColour(elementId) {
    var interval = 500;
    var colour1 = "#ff0000"
    var colour2 = "#000000";
    if (document.getElementById) {
        var element = document.getElementById(elementId);
        element.style.color = (element.style.color == colour1) ? colour2 : colour1;
        setTimeout("changeColour('" + elementId + "')", interval);
    }
}

//////////////////////////
// JQuery Round Corners //
//////////////////////////


//$(document).ready( function(){ $('.msg').corners('6px');});



$(document).ready( function(){ $('.StoreStock').corners('6px');});


$(document).ready( function(){ $('.WishListForm').corners('6px');});


///////////////////////////////
// Order Calculate functions //
///////////////////////////////

function RoundMe(numValue){
	return Math.round(numValue * 100) / 100;  //returns two digit decimal
}

function GetFields(){
    var numTotal = 0;
	var elem = document.getElementById('OrderForm').elements;
	var AdjustShipping = document.getElementById('AdjustShipping').value;
	var AdjustPST = document.getElementById('AdjustPST');
	var AdjustGST = document.getElementById('AdjustGST');

	var AdjustPSTRate = document.getElementById('AdjustPSTRate').value;
	var AdjustGSTRate = document.getElementById('AdjustGSTRate').value;

	for(var i = 0; i < elem.length; i++){
		if(elem[i].id == "AdjustPrice"){
			numValue = eval(elem[i].value);
			if(numValue > 0){
				numTotal = (numTotal + numValue);
			}
		}
	}

	numTotal = numTotal + eval(AdjustShipping);

	// apply taxes
	var TaxPST = ( AdjustPSTRate * numTotal / 100 );
	var TaxGST = ( AdjustGSTRate * numTotal / 100 );

	if(TaxPST > 0){
		numTotal = numTotal + eval(TaxPST);
		AdjustPST.value = RoundMe(TaxPST);
	}

	if(TaxGST > 0){
		numTotal = numTotal + eval(TaxGST);
		AdjustGST.value = RoundMe(TaxGST);
	}

	// return total
	document.getElementById('AdjustTotal').value = RoundMe(numTotal);
}

function ModifyOrder(){
	var answer = confirm("Are you sure you want to continue processing this order?");
	if(answer){
		return true;
	} else {
		return false;
	}
}

///////////////////
// PayPal Select //
///////////////////

function PaymentMethodSelect(){
    var PaymentMethod = document.Accounts.PaymentMethod;
    if(PaymentMethod[0].checked == true){
        document.getElementById("CreditCard").style.display  = '';
        document.getElementById("CreditCard2").style.display = '';
    } else {
        document.getElementById("CreditCard").style.display  = 'none';
        document.getElementById("CreditCard2").style.display = 'none';
    }
}


////////////////////////////////////////////////////////////

function GroupedProductImage(strImageName,strLargeImageLink,numChildProductID,numParentProductID,numProductPrice,numProductSKU,strProductName,strProductModel){


	// update sku
	//document.getElementById("ProvSku").value = numProductSKU;


	// product id
	document.getElementById("ProductsIDTemp").value = numChildProductID;

	// product name
	document.getElementById("ProductName").innerHTML = strProductName;

	// large image link
	document.getElementById("MainImageLink").href = strLargeImageLink;

	// add to cart link
	document.getElementById("AddToCartBtn").href = '/?page=products&ProductsID=' + numParentProductID + '&ChildProductID=' + numChildProductID + '&action=addtocart';

	// product price
	document.getElementById("ProductPrice").innerHTML = numProductPrice; // big product price
	document.getElementById("ProductPrice2").innerHTML = numProductPrice; // small product price

	// product SKU
	document.getElementById("ProductSKU").innerHTML = numProductSKU;

	// product Model
	document.getElementById("ProductModel").innerHTML = strProductModel;

	// product image
	MainImage = new Image();
	MainImage.src = strImageName;

	var MainImageOn = document.getElementById('MainProductImage');
	MainImageOn.src = MainImage.src;

	// NEW - set Stock Prov Drop Sku
	document.getElementById("ProvSku").value = numProductSKU;


	// load stock availability box
	loadStockAvailability();

}

//////////////////////

function HideShippingCredit(strTableName, FreeShippingValue){

	var myTableObj = document.getElementById(strTableName);
	if(FreeShippingValue.checked == true){
		myTableObj.style.display = ''
	} else {
		myTableObj.style.display = 'none'
	}
}

//////////////////////
function DisableButton(BtnEle){ BtnEle.disabled = true; }


function HideSchoolInput(strTableName, objCheckbox){

	var myTableObj = document.getElementById(strTableName);
	if(objCheckbox.checked == true){
		myTableObj.style.display = ''
	} else {
		myTableObj.style.display = 'none'
	}
}


function NumberOnly(evt) {
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        status = 'This field accepts numbers only.';
		alert(status);
        return false
    }
    status = '';
    return true
}


function AppendURL(){
	var AURL = document.getElementById('AddToCartBtn');
	var numQty = document.getElementById('Qty').value;
	var TempURL = AURL.href;
	var x = TempURL.lastIndexOf("&Qty");
	if (x != -1) {
		TempURL = TempURL.substr(0,x);
	}
	AURL.href = TempURL + '&Qty=' + numQty;
}

function ValidateGiftCardInput(){
	var CardNumber = document.getElementById('GiftcardNumber');
	if(CardNumber.value == ''){
		alert('You must enter a card number to continue.');
		return false;
	}
	return true;
}

function SelectProvFromProduct(Sku){

	var ProvObj = document.getElementById('ProvincesID');
	var ProvSelected = ProvObj.options[ProvObj.selectedIndex].value;
	var SkuTemp = document.getElementById("ProvSku");
	//alert(SkuTemp.value);

	if(ProvSelected > 0){
		location.href = '/instore_stock/' + SkuTemp.value + '/' + ProvSelected + '/';
	} else {
		return false;
	}

}

function SelectProv(){

	var ProvObj = document.getElementById('ProvincesID');
	var ProvSelected = ProvObj.options[ProvObj.selectedIndex].value;

	if(ProvSelected > 0){
		document.ProvFrm.submit();
	} else {
		return false;
	}
}


function HideStoreDrop(CheckOjb){

	var myTableObj = document.getElementById('LocationArea');

	if(CheckOjb.checked){
		myTableObj.style.display = '';
	} else {
		myTableObj.style.display = 'none';
	}
}

function EventsHomeDropJump(value){
	location.href='http://www.long-mcquade.com/events/' + value + '/';
}
