/**
 *	Custom site-wide JavaScript functions and classes for the Viking ATG consumer site.
 *	
 *	NOTES:
 *	- Some functions in this file rely heavily on other libraries, so make sure that 
 *	  this JavaScript library is loaded last
 *	
 *	@author Shaun Lessman
 *	@version $Id: global.js,v 1.40 2006/10/27 17:18:19 mvogel Exp $$Revision: 1.40 $
 *	@updated $Date: 2006/10/27 17:18:19 $$Author: mvogel $
 */


/**
 * Launch a new browser pop-up window
 *
 * @param mypage the url to load in the new window
 * @param myname the handle name of the new window
 * @param w the width of the window in pixels
 * @param h the height of the window in pixels
 **/
var win=null;
function NewWindow(mypage, myname, w, h) {
	myleft = (screen.width) ? (screen.width-w+60) / 2 : 100;
	mytop = (screen.height) ? (screen.height-h+70) / 2 : 100;
	
	winH = parseInt(h) + 70;
	winW = parseInt(w) + 60;
	
	settings = "width=" + winW + ",height=" + winH + ",top=" + mytop + ",left=" + myleft + ",scrollbars=no,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no";
	win = window.open(mypage, myname, settings);
	// win.href = mypage;
	win.focus();
}

var win=null;
function CheckoutNewWindow(mypage, myname, w, h) {
	myleft = (screen.width) ? (screen.width-w+60) / 2 : 100;
	mytop = (screen.height) ? (screen.height-h+70) / 2 : 100;
	
	winH = parseInt(h) + 70;
	winW = parseInt(w) + 60;
	
	settings = "width=" + winW + ",height=" + winH + ",top=" + mytop + ",left=" + myleft + ",scrollbars=yes,location=no,directories=no,status=yes,menubar=no,toolbar=no,resizable=yes";
	win = window.open(mypage, myname, settings);
	// win.href = mypage;
	win.focus();
}

/**
 * Submits the global logout form, logging the user out of the site
 **/
function doLogout () {
	$('logoutForm').submit();
}


/**
 * Submits the global logout and forward user form, logging the user out of the site
 **/
function doLogoutTo () {
	$('logoutToForm').submit();
}


/**
 * This instructs the prototype engine to run "init" upon 
 * "onLoad" for window.
 **/
Event.observe(window, 'load', init , false);


/**
 * Checkes for two special features and enables actions upon
 * related events on those pages.
 *
 * The code checks for these IDs on each page and enables
 * callback functions.
 * - country - for pages with a country/state drop-down
 * - docView - for the documentation section
 *
 **/
function init(){

	if (! $('checkoutErrorMessages') == "") {
		hideCheckoutErrors();
		Event.observe('checkoutErrorMessages', 'change', hideCheckoutErrors , false);
	}
	
	
	if (! $('contactUsForm') == "") {
		redrawContactUsView();
		Event.observe('contactUsForm', 'change', redrawContactUsView , false);
	}
	if (! $('country') == "") {
		reDrawStateRegion();
		Event.observe('country', 'change', reDrawStateRegion , false);
	}
	
	if (! $('docView') == "") {
		redrawDocView();
		Event.observe('docView', 'change', redrawDocView , false);
	}
	if (! $('careerId') == "") {
		redrawCareerView();
		Event.observe('careerId', 'change', redrawCareerView , false);
	}
	
	if (! $('designGalleryFilter') == "") {
		setSelectedChar();
		Event.observe('designGalleryFilter', 'change', setSelectedChar , false);
	}
	
	if (! $('newAddress') == "") {
		redrawAddressForm();

		// This works, not sure if it's more efficient than
		// putting them on each element as the loop below does
		// new Form.Observer('addressForm', 1, redrawAddressForm);

		var someNodeList = document.getElementsByClassName('vaddr','addressForm');
		var nodes = $A(someNodeList);
		nodes.each(function(node){
				new Form.Element.Observer(node, 0.2, redrawAddressForm);
			});
	}
	if (! $('recipeItemType') == "") {
		redrawRecipeFilter();
		Event.observe('recipeItemType', 'change', redrawRecipeFilter , false);
	}

	if (! $('productRegistration') == "") {
		displayProductType();
		// observe the initial drop-down
		Event.observe('productCat', 'change', displayProductType, false);
		// and all possible secondary drop-downs
		Event.observe('cookingTypesDD', 'change', redrawSerialFields, false);
		Event.observe('ventilationTypesDD', 'change', redrawSerialFields, false);
		Event.observe('refrigerationTypesDD', 'change', redrawSerialFields, false);
		Event.observe('kitchenCleanupTypesDD', 'change', redrawSerialFields, false);
		Event.observe('outdoorTypesDD', 'change', redrawSerialFields, false);
		Event.observe('cookwareCutleryTypesDD', 'change', redrawSerialFields, false);
		Event.observe('countertopAppliancesTypesDD', 'change', redrawSerialFields, false);
		Calendar.setup({
	        inputField     :    "datePurchased",      // id of the input field
	        ifFormat       :    "%m/%d/%Y",       // format of the input field
	        showsTime      :    false,            // will display a time selector
	        button         :    "datePurchased_Trigger",   // trigger for the calendar (button ID)
	        singleClick    :    true,           // double-click mode
	        step           :    1                // show all years in drop-down boxes (instead of every other year as default)
    	});
    	Calendar.setup({
	        inputField     :    "dateInstalled",      // id of the input field
	        ifFormat       :    "%m/%d/%Y",       // format of the input field
	        showsTime      :    false,            // will display a time selector
	        button         :    "dateInstalled_Trigger",   // trigger for the calendar (button ID)
	        singleClick    :    true,           // double-click mode
	        step           :    1                // show all years in drop-down boxes (instead of every other year as default)
    	}); 
	}
}

function redrawSerialFields() {
	// Lookup value of secondary selection (based on which drop-down is active)
	p = $F('productCat');
	if (p == 'Cooking') {
		v = $F('cookingTypesDD');
	} else if (p == 'Ventilation') {
		v = $F('ventilationTypesDD');
	} else if (p == 'Refrigeration') {
		v = $F('refrigerationTypesDD');
	} else if (p == 'Kitchen Cleanup') {
		v = $F('kitchenCleanupTypesDD');
	} else if (p == 'Outdoor') {
		v = $F('outdoorTypesDD');
	} else if (p == 'Cookware & Cutlery') {
		v = $F('cookwareCutleryTypesDD');
	} else if (p == 'Countertop Appliances') {
		v = $F('countertopAppliancesTypesDD');
	}

	NonSerial = 'Multi-Use Chamber Cabinets Grill Cart Cookware Cutlery Storage Drawer';
	UnknownProd = 'Unknown Cooking Product Unknown Ventilation Product Unknown Refrigeration Product Unknown Kitchen Cleanup Product Unknown Outdoor Product Unknown Cookware & Cutlery Product Unknown Countertop Appliances Product';

	if (v == '') {
		Element.hide('modelNumberField','serialNumberField');
	} else if (NonSerial.indexOf(v) != -1) {
		Element.update($('modelNumLabel'), 'N&uacute;mero do Modelo or Name of Product:');
		Element.show('modelNumberField');
		Element.hide('serialNumberField');
	} else if (UnknownProd.indexOf(v) != -1) {
		Element.update($('modelNumLabel'), 'Description of Product:');
		Element.update($('serialNumLabel'), 'Serial Number (if present):');
		Element.show('modelNumberField','serialNumberField');
	} else {
		// Main Important Integration Case - proper IB items
		Element.update($('modelNumLabel'), 'N&uacute;mero do Modelo:');
		Element.update($('serialNumLabel'), 'Serial Number:');
		Element.show('modelNumberField','serialNumberField','helperNote');
	}

	NoQuestions = 'Toaster Processor Mixer Blender';
	if (NoQuestions.indexOf(v) != -1) {
		Element.hide("optionalQuestions");	
	} else {
		Element.show("optionalQuestions");		
	}
}


/**
 * Toggles the visibility of correct drop down for product types
 **/
function displayProductType() {
	Element.hide("cookingTypes");
	Element.hide("ventilationTypes");
	Element.hide("refrigerationTypes");
	Element.hide("kitchenCleanupTypes");
	Element.hide("outdoorTypes");
	Element.hide("cookwareCutleryTypes");
	Element.hide("countertopAppliancesTypes");
	Element.hide("optionalQuestions");
	Element.hide('modelNumberField');
	Element.hide('serialNumberField');
	Element.hide('helperNote');
	p = $F('productCat');
	if (p == 'Cooking') {
		$("cookingTypesDD").value = "";
		Element.show("cookingTypes");
	} else if (p == 'Ventilation') {
		$("ventilationTypesDD").value = "";
		Element.show("ventilationTypes");
	} else if (p == 'Refrigeration') {
		$("refrigerationTypesDD").value = "";
		Element.show("refrigerationTypes");
	} else if (p == 'Kitchen Cleanup') {
		$("kitchenCleanupTypesDD").value = "";
		Element.show("kitchenCleanupTypes");
	} else if (p == 'Outdoor') {
		$("outdoorTypesDD").value = "";
		Element.show("outdoorTypes");
	} else if (p == 'Cookware & Cutlery') {
		$("cookwareCutleryTypesDD").value = "";
		Element.show("cookwareCutleryTypes");
	} else if (p == 'Countertop Appliances') {
		$("countertopAppliancesTypesDD").value = "";
		Element.show("countertopAppliancesTypes");
	}
};


/**
 * Toggles the visibility of new address form
 * MUST be used with an "Observer" rather than an "EventObserver"
 * Radio elements are not treated the same as others in prototype since
 * they are all separate elements.
 **/
function redrawAddressForm() {
  if ($F('newAddress') == "new") {
  	Element.show("newaddressform");
  } else {
  	Element.hide("newaddressform");
  }
};


/**
 * Show/Hide categories, or View All based 
 * on divs inside of #docView
 **/
function redrawDocView() {
	if ($F('docView') == "View All") {
		var someNodeList = document.getElementsByClassName('globalCategoryContainer');
		var nodes = $A(someNodeList);
		nodes.each(function(node) {
			Element.show(node);
		});
	} else {
		var someNodeList = document.getElementsByClassName('globalCategoryContainer');
		var nodes = $A(someNodeList);
		nodes.each(function(node) {
			if (node.id == $F('docView')) {
				Element.show(node);
			} else {
				Element.hide(node);
			}
		});
	}
}


/**
 * Show/Hide categories, or View All based 
 * on divs inside of #docViewForm
 **/
function redrawCareerView() {
	var someNodeList = $('Documents').getElementsByTagName('div');
	var nodes = $A(someNodeList);
	
	nodes.each(function(node) {
		if (node.id == $F('careerId')) {
			Element.show(node);
		} else {
			Element.hide(node);
		}
	});
}


/**
 * Show/Hide select boxes for recipe filter search
 **/
function redrawRecipeFilter() {
	
	var someNodeList = $('recipeFilterCategories').getElementsByTagName('div');

	var nodes = $A(someNodeList);
	
	nodes.each(function(node) {
		if (node.id == $F('recipeItemType')) {
			Element.show(node);
		} else {
			Element.hide(node);
		}
	});
}


/**
 * Show/Hide contact forms
 **/
function redrawContactUsView() {
	if ($F('contactUsForm') == 'CHOOSE_ONE') {
		Element.show($('CHOOSE_ONE'));
		Element.hide($('SITE_COMMENTS'));
		Element.hide($('PRODUCT_INFORMATION'));
		Element.hide($('CUSTOMER_SUPPORT'));
	} else if ($F('contactUsForm') == 'PRODUCT_INFORMATION') {
		Element.hide($('SITE_COMMENTS'));
		Element.show($('PRODUCT_INFORMATION'));
		Element.hide($('CUSTOMER_SUPPORT'));
	} else if ($F('contactUsForm') == 'CUSTOMER_SUPPORT') {
		Element.hide($('SITE_COMMENTS'));
		Element.hide($('PRODUCT_INFORMATION'));
		Element.show($('CUSTOMER_SUPPORT'));
	} else {
		Element.show($('SITE_COMMENTS'));
		Element.hide($('PRODUCT_INFORMATION'));
		Element.hide($('CUSTOMER_SUPPORT'));
	}
}

function hideCheckoutErrors() {
	Element.hide( "StartUnorderedList" );
	Element.hide( "FirstNameError" );
	Element.hide( "LastNameError" );
	Element.hide( "AddressError" );
	Element.hide( "CityError" );
	Element.hide( "StateError" );
	Element.hide( "PostalCodeError" );
	Element.hide( "PhoneError" );
	Element.hide( "EmailError" );
}


/**
 * Handle UI states for the country / region / state selection pages.
 * 3 states are (US, CA, else)
 **/
function reDrawStateRegion() {
	
	if ($F('country') == 'US') {
		$('state_region').disabled = false;
		Element.hide('regiontext');
		Element.show('state_region');
	} else if ($F('country') == 'CA') {
		$('state_region').disabled = false;
		Element.hide('regiontext');
		Element.show('state_region');
	} else {
		Element.hide('state_region');
		$('state_region').disabled = true;
		$('regiontext').disabled = false;
		Element.show('regiontext');
	}
}



function validateForm(form) {
	var success = true;
	
	// Checks all the values in the add new address form if the new address radio button is checked
	if( $('newAddress').checked ) {
		
		if(  !notEmpty( $F('FirstName') ) ) {
			Element.update ("FirstNameError", "<LI>You must supply a value for the 'First Name' field of this form.</LI> "); 
			Element.update( "FirstNameError", "<LI>You must supply a value for the 'First Name' field of this form.</LI> ");
			Element.show( "FirstNameError" );
			success = false;
		} else {
			Element.hide( "FirstNameError" );
		}
		
		if(  !notEmpty( $F('LastName') ) ) {
			Element.update ("LastNameError",  "<LI>You must supply a value for the 'Last Name' field of this form.</LI> "); 
			Element.show( "LastNameError" );
			success = false;
		} else {
			Element.hide( "LastNameError" );
		}
		
		if(  !notEmpty( $F('Address') ) ) {
			Element.update ("AddressError", "<LI>You must supply a value for the 'Address' field of this form.</LI> "); 
			Element.show( "AddressError" );
			success = false;
		} else {
			Element.hide( "AddressError" );
		}
		
		if(  !notEmpty( $F('City') ) ) {
			Element.update ("CityError",  "<LI>You must supply a value for the 'City' field of this form.</LI> "); 
			Element.show( "CityError" );
			success = false;
		} else {
			Element.hide( "CityError" );
		}
		
		if( $F('country') == 'US' || $F('country') == 'CA' ) {
			if(  $F('state_region') == '0' ) {
				Element.update ("StateError",  "<LI>You must supply a value for the 'State / Providence' field of this form.</LI> "); 
				Element.show( "StateError" );
				success = false;
			} else if (  $F('country') == 'US')  {
				if( $('state_region').options.selectedIndex  > '53' ) {
					Element.update ("StateError",  "<LI>The selected value for the 'State / Providence' field does not match the selected Country field of this form.</LI> "); 
					Element.show( "StateError" );
					success = false;
				} else {
					Element.hide( "StateError" );
				}
			} else if (  $F('country') == 'CA')  {
				if( $('state_region').options.selectedIndex  <= '53' ) {
					Element.update ("StateError",  "<LI>The selected value for the 'State / Providence' field does not match the selected Country field of this form.</LI>"); 
					Element.show( "StateError" );
					success = false;
				} else {
					Element.hide( "StateError" );
				}
			}
			else {
				Element.hide( "StateError" );
			}
		} else if( $F('regiontext') == "" ) {
			Element.update ("StateError",  "<LI>You must supply a value for the 'State / Providence' field of this form.</LI> "); 
			Element.show( "StateError" );
			success = false;
		} else  {
			Element.hide( "StateError" );
		}
		
		//-- Begin postal code check
		if(  !notEmpty( $F('PostalCode') ) ) {
			Element.update ("PostalCodeError",  "<LI>You must supply a value for the 'Postal Code' field of this form.</LI> "); 
			Element.show( "PostalCodeError" );
			success = false;
		} else if ( $F('country') == 'US' ) {
			if(  !jcv_isAllDigits( $F('PostalCode') ) ) {
				Element.update ("PostalCodeError",  "<LI>Postal code must be numeric.</LI>"); 
				Element.show( "PostalCodeError" );
				success = false;
			} else if ( $F('PostalCode').length != 5 ) {
				Element.update ("PostalCodeError",  "<LI>Postal code must be 5 digits.</LI>"); 
				Element.show( "PostalCodeError" );
				success = false;	
			} else {
				Element.hide( "PostalCodeError" );
			}
		} else if ( $F('country') == 'CA' ) {
			if (  $F('PostalCode').length < 5 ) {
				Element.update ("PostalCodeError",  "<LI>Postal code must be at least 5 digits.</LI>"); 
				Element.show( "PostalCodeError" );
				success = false;	
			} else {
				Element.hide( "PostalCodeError" );
			}
		}  else {
			Element.hide( "PostalCodeError" );
		}
		
		//-- Begin phone check
		if(  !notEmpty( $F('Phone') ) ) {
			Element.update ("PhoneError",  "<LI>You must supply a value for the 'Phone' field of this form.</LI> "); 
			Element.show( "PhoneError" );
			success = false;
		} else if (  $F('Phone').length < 10 ) {
			Element.update ("PhoneError",  "<LI>You supplied an invalid value for the 'Phone' field of this form. Your telephone number must be at least 10 numbers long, including area or country code.</LI>"); 
			Element.show( "PhoneError" );
			success = false;
		} else {
			Element.hide( "PhoneError" );
		}
		
	} else {
		hideCheckoutErrors();
	}
	if (! $('CreditCard') == "") {
		if(  !notEmpty( $F('CreditCard') ) ) {
				Element.update ("CreditCardError",  "<LI>You must supply a value for the 'Credit Card Number' field of this form.</LI> "); 
				Element.show( "CreditCardError" );
				success = false;
		} if (!jcv_luhnCheck( $F('CreditCard') ) ) {
				Element.update ("CreditCardError",  "<LI>You supplied an invalid 'Credit Card Number'.</LI>"); 
				Element.show( "CreditCardError" );
				success = false;
		}
		else {
			Element.hide( "CreditCardError" );
		}
	}
	
	if(  !notEmpty( $F('Email') ) ) {
		Element.update ("EmailError",  "<LI>You must supply a value for the 'Email' field of this form.</LI> "); 
		Element.show( "EmailError" );
		success = false;
	} else if ( !jcv_checkEmail( $F('Email') ) ) {
		Element.update ("EmailError",  "<LI>You supplied an invalid value for the 'E-mail Address' field of this form.</LI>"); 
		Element.show( "EmailError" );
		success = false;
	} else {
		Element.hide( "EmailError" );
	}
	
	if( !success ) {
		Element.show( "StartUnorderedList" );
	} else {
		Element.hide( "StartUnorderedList" );
	}
	
	return success;
}

function setSelectedChar() {
	var framesetQuery = "";
	if ( window.top.location.search != 0 ) {
		framesetQuery = window.top.location.search;
	} else {
		framesetQuery = "?OpenFrameset";
	}
	var value = getParameter( framesetQuery, "lastName" );
	if( value != "null" ) {
		Element.update (value,  "<FONT color='BLACK'><b>" + value +"</b></FONT>"); 
	}
}

function getParameter ( queryString, parameterName ) {
	// Add "=" to the parameter name (i.e. parameterName=value)
	var parameterName = parameterName + "=";
	if ( queryString.length > 0 ) {
		// Find the beginning of the string
		begin = queryString.indexOf ( parameterName );
		// If the parameter name is not found, skip it, otherwise return the value
		if ( begin != -1 ) {
			// Add the length (integer) to the beginning
			begin += parameterName.length;
			// Multiple parameters are separated by the "&" sign
			end = queryString.indexOf ( "&" , begin );
			if ( end == -1 ) {
				end = queryString.length
			}
			// Return the string
			return unescape ( queryString.substring ( begin, end ) );
		}
		// Return "null" if no parameter has been found
		return "null";
	}
}


