var DropDown = {
	// This function is used to show the drop down say Mini Shop Cart, Recentlt Viewed
	prevId:'',
	show:function(id) {
		var wipeArgs = {node:''};
		if(this.prevId != '') {
			dojo.byId(this.prevId).style.display = 'none';
		}
		if(dojo.byId(id) != null) {
			var element = dojo.byId(id);
			if(element.style.display == 'block') {
				return;
			}
			if(element.style.display == 'none') {
				this.prevId = id;
				wipeArgs = {node: id};
				dojo.fx.wipeIn(wipeArgs).play();
				dojo.style(id, "display", "block");
				wipeArgs = {node: ''};
				setTimeout(
					function() {
                		DropDown.hide(id);
		            },
    		        5000
    		    );
			}
		}
	},
	// This function is used to hide the drop down say Mini Shop Cart, Recentlt Viewed
	hide:function(id) {
		if(dojo.byId(id) != null) {
			var element = dojo.byId(id);
			element.style.display = 'none';
		}
	},
	showWithoutAnim:function(id){
		if(dojo.byId(id) != null) {
			var element = dojo.byId(id);
			element.style.display = 'block';
		}
	},
	hideShow:function(id) {
		if(dojo.byId(id) != null) {
			var element = dojo.byId(id);
			if(element.style.display == 'none') {
				element.style.display = '';
			} else {
				element.style.display = 'none';
			}
		}
	},
	// This function is used to show and hide the left side navigation in the catalog pages
	hideShowRefinement:function(id, list_id) {
		if(dojo.byId(list_id) != null) {
			var element = dojo.byId(list_id);
			if(element.style.display == 'none') {
				element.style.display = '';
				dojo.byId(id).removeClass;
			} else {
				element.style.display = 'none';
				dojo.byId(id).addClass('open');
			}
		}
	}
};

var CategoryView = {
	// Change view between list and grid
	changeView:function(id) {
		if(id != null) {
			if(id == 'listId1' || id == 'listId2') {
				if(id == 'listId2') {
					dojo.byId('listId1').focus();
				}
				dojo.addClass(dojo.byId('listId1'), 'selected');
				dojo.addClass(dojo.byId('listId2'), 'selected');				
				dojo.removeClass(dojo.byId('gridId1'), 'selected');
				dojo.removeClass(dojo.byId('gridId2'), 'selected');
			} else if(id == 'gridId1' || id == 'gridId2') {
				if(id == 'gridId2') {
					dojo.byId('gridId1').focus();
				}
				dojo.removeClass(dojo.byId('listId1'), 'selected');
				dojo.removeClass(dojo.byId('listId2'), 'selected');				
				dojo.addClass(dojo.byId('gridId1'), 'selected');
				dojo.addClass(dojo.byId('gridId2'), 'selected');
			}
		}
	}
};

var ProductDetailsTab = {
	// This function is used to switch between the tabs in the product detail page
	// Say Specification, Ratings, Know How and Accessories tabs
	switchTab:function(id) {
		var element = dojo.byId(id);
		if(element != null) {
			if(id == 'productDetailsTab_Accessory') {
				if(dojo.byId('BVSubmissionContainer') != null){
					dojo.byId('BVSubmissionContainer').style.display = 'none';
				}
				if(dojo.byId('BVReviewsContainer') != null){
					dojo.byId('BVReviewsContainer').style.display = 'none';
				}
				dojo.byId('productDetailsTab_Specification').style.display = 'none';
				dojo.byId('productDetailsTab_Knowhow').style.display = 'none';
				dojo.addClass(dojo.byId('productDetailsTabName_Accessory'),'active');
				dojo.removeClass(dojo.byId('productDetailsTabName_Rating'),'active');
				dojo.removeClass(dojo.byId('productDetailsTabName_Specification'),'active');
				if(dojo.byId('productDetailsTabName_KnowHow')!=null){
					dojo.removeClass(dojo.byId('productDetailsTabName_KnowHow'),'active');
				}
				element.style.display = '';
			} else if(id == 'productDetailsTab_Specification') {
				if(dojo.byId('BVSubmissionContainer') != null){
					dojo.byId('BVSubmissionContainer').style.display = 'none';
				}
				if(dojo.byId('BVReviewsContainer') != null){
					dojo.byId('BVReviewsContainer').style.display = 'none';
				}
				try {
				dojo.byId('productDetailsTab_Accessory').style.display = 'none';
				} catch (err) {
					//expect doesn't exist due to no accessories
				}
				dojo.byId('productDetailsTab_Knowhow').style.display = 'none';
				dojo.addClass(dojo.byId('productDetailsTabName_Specification'),'active');
				dojo.removeClass(dojo.byId('productDetailsTabName_Rating'),'active');
				try  {
				dojo.removeClass(dojo.byId('productDetailsTabName_Accessory'),'active');
					} catch (err) {
					//expect doesn't exist due to no accessories
				}
				if(dojo.byId('productDetailsTabName_KnowHow')!=null){
					dojo.removeClass(dojo.byId('productDetailsTabName_KnowHow'),'active');
				}
				element.style.display = '';
			}else if(id == 'BVReviewsContainer' || id == 'BVSubmissionContainer') {
			  try {
				dojo.byId('productDetailsTab_Accessory').style.display = 'none';
					} catch (err) {
					//expect doesn't exist due to no accessories
				}
				dojo.byId('productDetailsTab_Specification').style.display = 'none';
				dojo.byId('productDetailsTab_Knowhow').style.display = 'none';
				dojo.addClass(dojo.byId('productDetailsTabName_Rating'),'active');
				
				try {
				dojo.removeClass(dojo.byId('productDetailsTabName_Accessory'),'active');
					} catch (err) {
					//expect doesn't exist due to no accessories
				}
				
				dojo.removeClass(dojo.byId('productDetailsTabName_Specification'),'active');
				if(dojo.byId('productDetailsTabName_KnowHow')!=null){
					dojo.removeClass(dojo.byId('productDetailsTabName_KnowHow'),'active');
				}
				if(id == 'BVReviewsContainer' && dojo.byId('BVSubmissionContainer') != null){
					dojo.byId('BVSubmissionContainer').style.display = 'none';
				}
				if(id == 'BVSubmissionContainer' && dojo.byId('BVReviewsContainer') != null){
					dojo.byId('BVReviewsContainer').style.display = 'none';
				}
				element.style.display = '';
			}else if(id == 'productDetailsTab_Knowhow') {
				if(dojo.byId('BVSubmissionContainer') != null){
					dojo.byId('BVSubmissionContainer').style.display = 'none';
				}
				if(dojo.byId('BVReviewsContainer') != null){
					dojo.byId('BVReviewsContainer').style.display = 'none';
				}
				dojo.byId('productDetailsTab_Specification').style.display = 'none';
				try{
				dojo.byId('productDetailsTab_Accessory').style.display = 'none';
					} catch (err) {
					//expect doesn't exist due to no accessories
				}
				if(dojo.byId('productDetailsTabName_KnowHow')!=null){
					dojo.addClass(dojo.byId('productDetailsTabName_KnowHow'),'active');
				}
				dojo.removeClass(dojo.byId('productDetailsTabName_Rating'),'active');
				dojo.removeClass(dojo.byId('productDetailsTabName_Specification'),'active');
				try {
				dojo.removeClass(dojo.byId('productDetailsTabName_Accessory'),'active');
					} catch (err) {
					//expect doesn't exist due to no accessories
				}
				element.style.display = '';
			}
			element.focus();
		}
	}
};


var QuickView = {
	// This object has methods to show & hide the Quick View button on the Product Thumbnails
	// This function opens the popup
	show:function(backroundId, contentId) {
		if(dojo.byId(backroundId) != null && dojo.byId(contentId) != null) {
			dojo.byId(backroundId).style.display='';
			dojo.byId(contentId).style.display='';			
		}
	},
	
	// This function will close the popup
	hide:function(backroundId, contentId) {
		if(dojo.byId(backroundId) != null && dojo.byId(contentId) != null) {
			dojo.byId(backroundId).style.display='none';
			dojo.byId(contentId).style.display='none';			
		}
	},
	
	// This function will show the Quick View button if the mouse poiner hovers on the product image in the category |} search results page
	showHideButton:function(id) {
		if(dojo.byId(id) != null) {
			if(dojo.byId(id).style.display == 'none') {
				dojo.byId(id).style.display = '';
			} else {
				dojo.byId(id).style.display = 'none';
			}
		}
	}
	
}

var CompareToolBar = {
	// Opens the Compare toolbar
	show:function() {
		if(dojo.byId('compareText') != null) {
			var compareElement = dojo.byId('compare');
			var compareWrapperElement = dojo.byId('compareWrapper');
			if(compareWrapperElement!=null){
				dojo.addClass(compareElement, 'open_compare');
				dojo.byId("contentContainer").style.display = 'none';
				scroll(0,0);
			}else{
				dojo.addClass(compareElement, 'open');			
			}
		}
	},
	
	// Hides the compare toolbar
	hide:function() {
		if(dojo.byId('compareText') != null) {
			var compareElement = dojo.byId('compare');
			var compareWrapperElement = dojo.byId('compareWrapper');
			if(compareWrapperElement!=null){
				dojo.removeClass(compareElement, 'open_compare');
			}else{
				dojo.removeClass(compareElement, 'open');			
			}			
			CompareProducts.isCompare=false;
		}
	}
};

var LeftNavigation = {
	// On hover of top category shows the subcategory
	showSubCategory:function(topCatId, subCatId) {
		if(dojo.byId(subCatId) != null) {
			var element = dojo.byId(subCatId);
			element.style.display = '';
			dojo.addClass(dojo.byId(topCatId), 'active');
		}
	},
	
	// Hides when mouse moves out of the top or subcategory which ever is selected
	hideSubCategory:function(topCatId, subCatId) {
		if(dojo.byId(subCatId) != null) {
			var element = dojo.byId(subCatId);
			element.style.display = 'none';
			dojo.removeClass(dojo.byId(topCatId), 'active');
		}
	},
	
	// Show or Hide the Categories in the left navigation if user clicks on the browse product button
	hideShowCategoryNavigation:function(id) {
		var wipeArgs = {
	        node: id
        };
		if(dojo.byId(id) != null) {
			var element = dojo.byId(id);
			if(element.style.display == 'block') {
				dojo.style(id, "display", "block");
				dojo.fx.wipeOut(wipeArgs).play();
			} else {
				dojo.style(id, "display", "none");
				dojo.fx.wipeIn(wipeArgs).play();
				element.style.display = 'block';
			}
		}
	},
	
	// Show or Hide the refinements in the left refinements if user clicks on the refinement name
	hideShowRefinementsList:function(id) {
		wipeArgs = {node: id};
		if(dojo.byId(id) != null) {
			var element = dojo.byId(id);
			var headElement = id.replace('group_list', 'refine_name');
			if(element.style.display == 'none') {
				dojo.addClass(dojo.byId(headElement),'open');
				dojo.fx.wipeIn(wipeArgs).play();
			} else {
				dojo.removeClass(dojo.byId(headElement), 'open');
				dojo.fx.wipeOut(wipeArgs).play();
			}
		}
		
	}
};

var Page = {
	// Redirects the page 
	redirect:function(url){
		window.location = url;
	}
};

var CookieUtil = {
	// This object has methods defined for cookie manipulation
	createCookie:function(cookieName, cookieValue, expiryTime, isJSONFormat) {
		// Creates the Cookie with the specified parameters. 
		// If supplied value is a JSON
		if(isJSONFormat) {
			dojo.cookie(cookieName, dojo.toJson(cookieValue), {expires:expiryTime});
		} else {	// If supplied value is normal
			dojo.cookie(cookieName, cookieValue, expiryTime);
		}
	},
		
	removeCookie:function(cookieName) {
		// Deletes the cookie whose name is supplied , sets the expiry parameter to -1
		dojo.cookie(cookieName, null, {expires:-1});
	},
		
	getJSONCookie:function(cookieName) {
		// Returns the value of the supplied cookie name
		var cookie = dojo.fromJson(dojo.cookie(cookieName));
		return cookie;
	},
	
	getCookies:function() {
		// Returns the cookie for the document,  Returns [<cookiename1>:<cookievalue1>,<cookiename2>:<cookievalue2>, ... <cookienamen><cookievaluen>]
		var cookies = document.cookie.split(';');
		var i = 0;
		var cookieList = new Array();
		for(i=0; i<cookies.length; i++) {
			cookieList[i] = cookies[i].split(',');
		}
		return cookieList;
	}
	
};

var TradingHour = {
	// This object has properties and methods related to Store Trading Hours functionality
	delimitter:'_',
	maxNumberOfCachedEntries:10,
	tradingHourDate:'',
	tradingHourDateObj:'',
	openTime:'',
	closeTime:'',
	
	// This set how many days needs to be cached
	setMaxCachedEntries:function(value) {
		this.maxNumberOfCachedEntries = value;
	},
	
	setDelimitter:function(value) {
		// Sets trading hour cookie name delimitter
		this.delimitter = value;
	},
	
	isCached:function(dateObj) {
		// Checks Trading hours for the day is cached or not. Returns true if cached else false
		var cookieName = this.constructCookieName(dateObj);
		if(dojo.cookie(cookieName) != undefined) {
			console.debug('Trading hours cached. Reading from the cookie');
			return true;
		} else {
			return false;
		}
	},
	
	getTradingHourCookies:function() {
		// This method will return only the trading hour cookies
		var cookies = CookieUtil.getCookies();
		var tradingHourCookieJSON = '';
		var tradingHourCookies = new Array();
		for(var i=0; i<cookies.length; i++) {
			console.debug('Trading Hour Cookies : ' + cookies[i][0]);
			if(cookies[i][0].indexOf('tgg_tradinghours') != -1) {
				tradingHourCookieJSON = {cookieName:cookies[i][0].split('=')[0], cookieValue:cookies[i][0].split('=')[1]};
				tradingHourCookies.push(tradingHourCookieJSON);
			}
		}
		return tradingHourCookies;
	},
	
	getSizeOfCache:function() {
		// Should return the number of cached trading hours i,e should return the number of trading hour cookies
		if(this.getTradingHourCookies() != null) {
			return this.getTradingHourCookies().length;
		}
		return 0;
	},
		
	nextDayTradingHour:function() {
		// Should get the trading hour of next day relative to current displayed date. First check for cache, if not found go to server &
		// fetch the data
		var nextDate = DateUtil.getNextDate();
		this.tradingHourDateObj = nextDate;
		if(this.isCached(nextDate)) {
			var nextDayCookie = this.constructCookieName(nextDate);
			var tradingHours = CookieUtil.getJSONCookie(nextDayCookie);
			console.debug('Trading Hours from cookie : openTime - ' + tradingHours.openTime + ', closeTime - ' + tradingHours.closeTime);
			this.updateTradingHourDisplay(tradingHours);
		} else {
			// Do an AJAX call to fetch data from the server & cache the information by creating a cookie
			// Check cache size.. if it reaches the defined limit, then call removeFirstCachedTradingHour and then create a cookie
			if(this.getSizeOfCache() >= this.maxNumberOfCachedEntries) {
				this.removeFirstCachedTradingHour();
			}
			this.tradingHourDate = DateUtil.formatDate(nextDate, 'TRADINGHOURS');
			var param = {"date":DateUtil.formatDate(nextDate, "yyyy-mm-dd")};
			this.getTradingHourFromServer('AjaxTradingHourDisplay', param);
		}
	},
	
	previousDayTradingHour:function() {
		// Should get the trading hour of previous day relative to current displayed date. First check for cache, if not found go to server &
		// fetch the data
		var previousDate = DateUtil.getPreviousDate();
		this.tradingHourDateObj = previousDate;
		if(this.isCached(previousDate)) {
			var prevDayCookie = this.constructCookieName(previousDate);
			var tradingHours = CookieUtil.getJSONCookie(prevDayCookie);
			console.debug('Trading Hours from cookie : openTime - ' + tradingHours.openTime + ', closeTime - ' + tradingHours.closeTime);
			this.updateTradingHourDisplay(tradingHours);
		} else {
			// Do an AJAX call to fetch data from the server & cache the information by creating a cookie
			// Check cache size.. if it reaches the defined limit, then call removeFirstCachedTradingHour and then create a cookie
			if(this.getSizeOfCache() >= this.maxNumberOfCachedEntries) {
				this.removeFirstCachedTradingHour();
			}
			this.tradingHourDate = DateUtil.formatDate(previousDate, 'TRADINGHOURS');			
			var param = {"date":DateUtil.formatDate(previousDate, "yyyy-mm-dd")};
			this.getTradingHourFromServer('AjaxTradingHourDisplay', param);
		}
	},
	
	currentDayTradingHour:function() {
		// Set the current day trading hour once the page loads, Called only during the entire page load
		// Should get the trading hour of current day relative to current displayed date. First check for cache, if not found go to server &
		// fetch the data
		var currentDate = DateUtil.getCurrentDate();
		this.tradingHourDateObj = currentDate;
		
		if(this.isCached(currentDate)) {
			var currDayCookie = this.constructCookieName(currentDate);
			var tradingHours = CookieUtil.getJSONCookie(currDayCookie);
			console.debug('Trading Hours from cookie : openTime - ' + tradingHours.openTime + ', closeTime - ' + tradingHours.closeTime);
			this.updateTradingHourDisplay(tradingHours);
		} else {
			// Do an AJAX call to fetch data from the server & cache the information by creating a cookie
			// Check cache size.. if it reaches the defined limit, then call removeFirstCachedTradingHour and then create a cookie
			if(this.getSizeOfCache() >= this.maxNumberOfCachedEntries) {
				this.removeFirstCachedTradingHour();
			}
			this.tradingHourDate = DateUtil.formatDate(currentDate, 'TRADINGHOURS');			
			var param = {"date":DateUtil.formatDate(DateUtil.getCurrentDate(), "yyyy-mm-dd")};
			this.getTradingHourFromServer('AjaxTradingHourDisplay', param);
		}
	},
	
	updateTradingHourDisplay:function(jsonObj) {
		var result = DateUtil.formatDate(this.tradingHourDateObj, 'TRADINGHOURS') + '<br/>'; 
		//Fix for Defect ID 631 - Start
		if(jsonObj.openTime != '' && jsonObj.closeTime != '' && jsonObj.openTime != '00:00am' && jsonObj.closeTime != '00:00am') {
		//Fix for Defect ID 631 - End
			result = result + jsonObj.openTime + ' ' + jsonObj.closeTime;
		} else { // If open time and close time are empty, then set the result to CLOSED
			result = result + 'CLOSED';
		}
		// Setting the trading hours to the DOM
		dojo.byId('times').innerHTML = result;
	},
	
	constructCookieName:function(dateObj) {
		// This will construct the cookie name [tgg_tradinghours_<storeId>_<date>_<cookie creation time in ms>]
		var cookieName = 'tgg' + this.delimitter + 'tradinghours' + this.delimitter + StoreUtil.getStoreId() + this.delimitter + DateUtil.formatDate(dateObj, 'dd-mm-yyyy');
		console.debug('Cookie name : ' + cookieName);
		return cookieName;
	},
	
	removeFirstCachedTradingHour:function() {
		// This function will remove the first cached entry if the cache size reaches the limit (Default Cache Size = 10)
		var tradingHourCookies = this.getTradingHourCookies();
		var tradingHourCookieJSON = '';
		var cookieName = '';
		var cookieCreatedTimeInMs = '';
		var cookieCreatedTimeList = new Array();
		// Iterate the tradinghour cookies to get the list of cookie creation times
		for(var i=0; i<tradingHourCookies.length;i++) {
			tradingHourCookieJSON = tradingHourCookies[i];
			cookieName = dojo.trim(tradingHourCookieJSON.cookieName);
			cookieCreatedTimeInMs = CookieUtil.getJSONCookie(cookieName).cookieCreationTime;
			cookieCreatedTimeList.push(cookieCreatedTimeInMs);
		}
		
		// Sort the time list so that we can get the min time i,e first cookie creation time
		cookieCreatedTimeList.sort();
		var firstCreatedCookieTime = '';
		
		for(var i=0; tradingHourCookies != null && i<tradingHourCookies.length; i++) {
			if(cookieCreatedTimeList != null && cookieCreatedTimeList.length > 0) {
				firstCreatedCookieTime = cookieCreatedTimeList[0];
			}
			tradingHourCookieJSON = tradingHourCookies[i];
			// Get the cookie name which has the least creation time and call removeCookie method to delete the first cached cookie
			cookieName = dojo.trim(tradingHourCookieJSON.cookieName);
			cookieCreatedTimeInMs = CookieUtil.getJSONCookie(cookieName).cookieCreationTime;
			if(cookieCreatedTimeInMs == firstCreatedCookieTime) {
				CookieUtil.removeCookie(tradingHourCookieJSON.cookieName);
			}
		}
	},
	
	// This function will retrieve current day trading hours from the Server
	getTradingHourFromServer:function(url, param) {
		dojo.xhrGet(
			{
				url:url,
				handleAs:'json-comment-filtered',
				content:param,
				sync:true,
				load:function(responseJSON, ioArgs) {
					console.debug('Open Time : ' + responseJSON.result.openTime + ', Close Time : ' + responseJSON.result.closeTime);
					var result = TradingHour.tradingHourDate + '<br/>'; 
					//Fix for Defect ID 631 - Start
					if(responseJSON.result.openTime != '' && responseJSON.result.closeTime != '' && responseJSON.result.openTime != '00:00am' && responseJSON.result.closeTime != '00:00am') {
					//Fix for Defect ID 631 - End
						result = result + responseJSON.result.openTime + ' - ' + responseJSON.result.closeTime;
					} else { // If open time and close time are empty, then set the result to CLOSED
						result = result + 'CLOSED';
					}
					// Setting the trading hours to the DOM
					dojo.byId('times').innerHTML = result;
					// Constructs the cookie with openTime, closeTime & cookie creation time in ms.
					// Cookie creation time is used to remove the first created cookie if cookie count exceed the specified limit
					var cookieValue = {openTime:responseJSON.result.openTime, closeTime:responseJSON.result.closeTime, cookieCreationTime:'' + new Date().getTime()};
					// Creating the Cookie
					CookieUtil.createCookie(TradingHour.constructCookieName(TradingHour.tradingHourDateObj), cookieValue, eval(30/86400), true);
					console.debug('Trading Hour is cached in the cookie');
				}
			}
		);
	}
	
};

var DateUtil = {
	// This object has the methods defined for date utilites
	currentDate:new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()),
	month:new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'),
	day:new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat'),
	datePostFix:new Array('st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'),
	
	getCurrentDate:function() {
		// returns the current date
		var currDate;
		if(dojo.isIE == '6' || dojo.isIE == '7' || dojo.isIE == '8') {
			currDate = new Date(new Date().getFullYear()-1900, new Date().getMonth(), new Date().getDate());
			this.currentDate = currDate;
		} else {
			currDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
		}
		return currDate;
	},
	
	getNextDate:function() {
		// Return the next date
		var nextDate;
		nextDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), this.currentDate.getDate()+1);
		this.currentDate = nextDate;
		return nextDate;
	},
	
	getPreviousDate:function() {
		// Return the previous date
		var previousDate;
		previousDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), this.currentDate.getDate()-1);
		this.currentDate = previousDate;
		return previousDate;
	},
	
	formatDate:function(dateObj, format) {
		// This function formats the date based on the format supplied
		var date = dateObj.getDate();
		var month = dateObj.getMonth() + 1;
		var year = dateObj.getYear() + 1900;
		var formattedDate = '';
		
		if(format == 'TRADINGHOURS') {
			// Formats the date [Sep, Thurs 22nd]
			var formatDateObj = new Date((dateObj.getYear() + 1900), dateObj.getMonth(), dateObj.getDate())
			var day = new Array(7);
			var monthInString = this.month[dateObj.getMonth()];
			var dateInString = dateObj.getDate() + '' + this.datePostFix[dateObj.getDate()-1];
			var dayOfWeek = this.day[formatDateObj.getDay()];
			formattedDate = dayOfWeek + ', ' + monthInString + ' ' + dateInString;
			return formattedDate;
		} else if (format == 'dd-mm-yyyy') {
			// Returns the date in dd-mm-yyyy format
			if(date.length == 1) {
				date = '0' + date;
			}
			if(month.length == 1) {
				month = '0' + month;
			}
			formattedDate = date + '-' + month + '-' + year;
			return formattedDate;
		} else if (format == 'yyyy-mm-dd') {
			// Returns the date in yyyy-mm-dd format
			if(date.length == 1) {
				date = '0' + date;
			}
			if(month.length == 1) {
				month = '0' + month;
			}
			formattedDate = year + '-' + month + '-' + date;
			return formattedDate;
		}
	}
	
};

var StoreUtil = {
	// This returns the current Store ID - Reads the global variable from the head.jspf
	getStoreId:function() {
		return storeId;
	}
};

var CategoriesDisplay = {
	
	elementValue:'',
	// This function sets the page size in the categories display product filtering - Setting the number of products to be displayed
	setPageSize:function(formId, currentId, URL) {
		var form = dojo.byId(formId);
		if(form.pageSize.value == this.elementValue) {
			return;
		}
		this.elementvalue = form.pageSize.value;
		
		CommonControllersDeclarationJS.setControllerFormId('CategoryDisplay_Controller', formId);
		setCurrentId(currentId); 
		categoryDisplayJS.loadContentURL(URL);
		dojo.byId('pageSizeForm1').focus();
	}
}

var Util = {
	// This function will clear the text in the text boxes if any default values are available
	// For instance, in the Search text field, by default 'Search' will be populated. This function will clear it using onclick event
	clearText:function(id) {
		if(dojo.byId(id)) {
			var value = dojo.byId(id).value;
			if(value != null && (value == 'Search' || value == 'Enter your email')) {
				dojo.byId(id).value = '';
			}
		}
	},
	
	// This will show the overlay
	showOverlay:function(id) {
		if(id!='' && id!=null && dojo.byId(id)!=null) {
			dojo.byId(id).style.display = 'block';	
			if(dojo.byId("closeButton")!=null) {
				//dojo.byId("closeButton").focus();
			}
		
		}
	},
	// This will hide the overlay
	hideOverlay:function(id) {
		if(id!='' && id!=null && dojo.byId(id)!=null) {	
			dojo.byId(id).style.display = 'none';	
		}
	},
	hidePageSuccessMsgForWishlist:function(){
		dojo.query("#confirmation").orphan();
	},
	// This function will hide the page error messages
	hidePageErrorMsgs:function() {
		dojo.query(".fn_valid_mandatory").removeClass("fn_valid_mandatory error").addClass("fn_valid_mandatory");
		dojo.query(".inlineError").orphan();
		dojo.query("#errors").orphan();
		dojo.query("#confirmation").orphan();
	},
	clickCheckBox:function(id) {
		dojo.byId(id).checked = true;
	}
};


var MyAccountUtil = {

	addParams:function(formId, optId) {
		//var selIndex = dojo.byId(optId).selectedIndex;
		var pageURL = formId.action;
		if(optId == 'selSort1' || optId == 'selSort2' ){
			pageURL+="&selectOption="+dojo.byId(optId).selectedIndex;
		}else if(optId == 'selItems1' || optId == 'selItems2'){
			pageURL+="&pageSize="+dojo.byId(optId).value;		
		}
		AccountWishListDisplay.loadContentURL(pageURL);
	},
	
	validateAddressByQAS:function(url,params,formId,pageName, jsSvcNameForAdrBook) {
		wc.service.getServiceById("QASAddressValidate").url=url;
		wc.service.getServiceById("QASAddressValidate").formId=formId;
		wc.service.getServiceById("QASAddressValidate").page=pageName;
		if(jsSvcNameForAdrBook!=''){
			wc.service.getServiceById("QASAddressValidate").jsSvcNameForAddrBook = jsSvcNameForAdrBook;
		}
		wc.service.invoke("QASAddressValidate",params);
	},
	
	prepSubmit:function(form1,pageId,svcName) {
		var addrss = document.getElementsByName('first_address');
		if(addrss!=null){
			if(addrss.length == 0 || addrss.length == undefined){
				addrss = new Array();
				addrss.push(document.getElementsByName('first_address'));
			}
			dojo.forEach(addrss, function(addrEntry) {
				if(addrEntry.checked) {
					var checkedAddr = dojo.trim(addrEntry.value);
					console.debug(checkedAddr);
					if(checkedAddr == "none") {
						if(pageId == 'Register' || pageId == 'shoppingCartShippingBilling') {
							form1.submit();
						}
						else if(pageId == 'ProfileUpdate'){
							wc.service.invoke('UserRegistrationUpdate');						
						}
						else if(pageId == 'AddressBook'){
							wc.service.invoke(svcName);
						}
					}
					else if(pageId == 'shoppingCartShippingBilling'){
						var addr_array = checkedAddr.split("|||");
						console.debug(addr_array[0]+" "+addr_array[1]+"q"+addr_array[2]+"w"+addr_array[3]+"e"+addr_array[4]+"r"+addr_array[5]);
						form1.address1.value = addr_array[0];
						form1.address2.value = addr_array[1];
						form1.city.value = addr_array[2];
						form1.zipCode.value = addr_array[4];
						form1.addressField2.value = addr_array[6];
						
						var billPickSelect = form1.billing_pickup_radio;
						var billSelect = ''; 
						if(billPickSelect!=null){
							var billPickChecked = false;
							dojo.forEach(billPickSelect, function(billPickEntry) {
								if(billPickEntry.checked) {
									billSelect = billPickEntry.value;
								}
							});	
						}
						if(billSelect=='S'){
							form1.billing_pickup_address_1.value = addr_array[0];
							form1.billing_pickup_address_2.value = addr_array[1];
							form1.billing_pickup_suburb.value = addr_array[2];
							form1.billing_pickup_postcode.value = addr_array[4];
						}
						Util.hideOverlay('addressWrapper'); 
						Util.hideOverlay('overlayBackground');
						form1.submit();
					} 
					else {
						var addr_array = checkedAddr.split("|||");
						console.debug(addr_array[0]+" "+addr_array[1]+" "+addr_array[2]+" "+addr_array[3]+" "+addr_array[4]+" "+addr_array[5]);
						form1.address1.value = addr_array[0];
						form1.address2.value = addr_array[1];
						form1.city.value = addr_array[2];
						form1.zipCode.value = addr_array[4];
						form1.addressField2.value = addr_array[6];
						if(pageId == 'Register') {
							form1.submit();
						}
						else if(pageId == 'ProfileUpdate'){
							wc.service.invoke('UserRegistrationUpdate');						
						}
						else if(pageId == 'AddressBook'){
							wc.service.invoke(svcName);
						}
					}
				}
			});
		}
	},
	prepSubmitForAddrBook:function(form1,pageId) {
		var cssDispStyle = dojo.byId('content_footer').style.display;
		if(cssDispStyle == '' || cssDispStyle == 'block') {
			this.prepSubmit(form1,pageId,'updateAddressBook');
		}
		else if(cssDispStyle == 'none'){
			this.prepSubmit(form1,pageId,'updateAddress');
		}
	},
	updateDropdown:function(availableList,selectOption){
		var selectedIndex = dojo.byId('personal_info_store_state').selectedIndex;
		if(selectedIndex == null){
			return;
		}
		var stateIndex = dojo.byId('personal_info_store_state').options[selectedIndex].value;
		var entries = availableList[stateIndex]?availableList[stateIndex]:{};
		
		// Add new options
		var html = '<option value="">Select</option>';
		for(var key in entries){
			if(selectOption == key) {
				html += '<option value="'+key+'" selected>'+entries[key]+'</option>';
			}
			else{
				html += '<option value="'+key+'">'+entries[key]+'</option>';
			}
		}
		if(dojo.isIE == '6' || dojo.isIE == '7' || dojo.isIE == '8' || dojo.isIE == '9'){
			dojo.byId('personal_info_store_location').innerHTML = '<option value="">Select</option>'+html;
		}else{
			dojo.byId('personal_info_store_location').innerHTML = html;	
		}
		dojo.byId('personal_info_store_location').outerHTML = dojo.byId('personal_info_store_location').outerHTML;
	}
};

var Inventory = {
	getInventory:function(AjaxCheckInventoryURL) {
		cursor_wait();
		document.getElementById("StockCheck").style.display = ("none");
		wc.service.getServiceById("AjaxCheckInventory").url=AjaxCheckInventoryURL;
		wc.service.invoke("AjaxCheckInventory");
	}
};

var CheckAvail = {
	contactStore:function() {
		document.getElementById("Contact_Store").innerHTML = "Out of Stock";
	}
}

var ExtendedWarranty = {
	// This method will extract the product Id from the input <productId>_<ProductPrice>
	getProductId:function(val) {
		if(val != null) {
			return val.split('_')[0];
		}
	},
	// This method will extract the product price from the input <productId>_<ProductPrice>
	getProductPrice:function(val) {
		if(val != null) {
			var price = '' + val.split('_')[1];
			if(price == 'undefined') {
				return 0.0;
			}
			return price;
		} 
	},
	// This method calculate the subtotal to be displayed on the product display page
	calculateSubTotal:function(extWarrantyPrice) {
		var parentProductArray = eval(dojo.byId('parentProductPrice').innerHTML);
		var parentProductPrice = parentProductArray[0];
		var subtotal = eval(parentProductPrice.price) + eval(extWarrantyPrice);
		if(subtotal > 100) {
			dojo.byId('subtotal').innerHTML = '<sup>= $</sup>' + dojo.number.format(subtotal, { places:0, pattern:'#0' });
		} else {
			dojo.byId('subtotal').innerHTML = '<sup>= $</sup>' + dojo.number.format(subtotal, { places:2, pattern:'#0.00' });
		}
	},
	// This method will calculate the subtotal to be displayed in the ext warranty overlay in shopping cart
	updatePriceWithExtWarranty:function() {
		var extWarrantyId;
		for (var i=0; i < document.extWarrantyAdd.catEntryId_1.length; i++) {
		   if (document.extWarrantyAdd.catEntryId_1[i].checked){
		   		extWarrantyId  = document.extWarrantyAdd.catEntryId_1[i].value;
		   }
	    }
	    var extWarrantyObjects = eval(dojo.byId('shopCart_ExtWarrantyPricing').innerHTML);
	    var parentProductPriceObject = eval(dojo.byId('shopCart_ParentProductPrice').innerHTML);
	    dojo.forEach(extWarrantyObjects, function(extWarrantyObject) {
	    	if(extWarrantyObject.extWarrantyId == extWarrantyId) {
	    		var subtotal = eval(parentProductPriceObject) + eval(extWarrantyObject.extWarrantyPrice);
	    		dojo.byId('shopCart_subtotal').innerHTML = '<sup>$</sup>'+ dojo.number.format(subtotal, { places:2, pattern:'#0.00' });
	    	}
	    }
	    );
	}
};

var ImageGallery = {
	largeImagesArr: '',
	thumbnailImagesArr: '',
	index:0,
	
	// This method should be called before calling any methods in this object; This initializes the source
	init:function() {
		this.largeImagesArr = eval(dojo.byId('fullImageAttachments').innerHTML);
		
		this.thumbnailImagesArr = eval(dojo.byId('thumbnailAttachments').innerHTML);
	},
	// This method return the number of images in the list
	getSize:function() {
		return this.largeImagesArr.length;
	},
	// This method will move to the next image
	nextImage:function() {
	
		this.index = eval(this.index + 1);
			if(this.index == this.getSize() - 1) {
			dojo.byId('nextImageButton').style.display = 'none';
		} 
		dojo.byId('productMainImage').src = this.decodeImageUrl(this.largeImagesArr[eval(this.index)]);
	
		
		dojo.addClass(dojo.byId('thumbnail_'+eval((this.index)+1)), 'active');
		if(dojo.byId('thumbnail_'+(eval(this.index))) != null) {
		
			dojo.removeClass(dojo.byId('thumbnail_'+(eval(this.index))), 'active');
		}
		if(dojo.byId('prevImageButton').style.display == 'none') {
			dojo.byId('prevImageButton').style.display = 'block';
		}
		dojo.byId('productMainImage').focus();
		
	},
	// This method will move to the previous image
	prevImage:function() {
		this.index = eval(this.index - 1);	

		dojo.byId('productMainImage').src = this.decodeImageUrl(this.largeImagesArr[this.index]);
		
		dojo.addClass(dojo.byId('thumbnail_'+ eval(this.index+1)), 'active');
		if(dojo.byId('thumbnail_'+eval(this.index+2)) != null) {
			dojo.removeClass(dojo.byId('thumbnail_'+eval(this.index+2)), 'active');
		}
		
		
		if (this.index > 0) {
		     dojo.byId('prevImageButton').style.display = 'block';
		} else {
		 dojo.byId('prevImageButton').style.display = 'none';
		}
		if (this.index < eval(this.getSize()+1)){
		dojo.byId('nextImageButton').style.display = 'block';
		} else {
		dojo.byId('nextImageButton').style.display = 'none';
		}
		
		
		dojo.byId('productMainImage').focus();
			
	},
	// This method will change the large image based on which thumbnail is selected
	changeImage:function(id) {
		var li = dojo.query('#imageGalleryThumbnails  > li');
		dojo.forEach(li, function(item) {
		    dojo.removeClass(item, 'active');
		});
		dojo.addClass(dojo.byId(id), 'active');
		var largeImageIndex = id.split('_')[1]-1;
	
		if(largeImageIndex == '0' && this.getSize() > 1) {
			dojo.byId('prevImageButton').style.display = 'none';
			dojo.byId('nextImageButton').style.display = 'block';
		}
		if(largeImageIndex == this.getSize()-1 && this.getSize() > 1) {
			dojo.byId('nextImageButton').style.display = 'none';
			dojo.byId('prevImageButton').style.display = 'block';
		}
		if(largeImageIndex > 0 && largeImageIndex < this.getSize()-1) {
			dojo.byId('prevImageButton').style.display = 'block';
			dojo.byId('nextImageButton').style.display = 'block';
		}
	    
		var currentSrc = dojo.byId('productMainImage').src;
	   var srcUrlIndexArray = currentSrc.split('/');
	  
		dojo.byId('productMainImage').src = this.decodeImageUrl(this.largeImagesArr[largeImageIndex]);
		this.index = largeImageIndex;
	},
	decodeImageUrl:function(str){
		/*Firefox (and IE if the string contains no elements surrounded by angle brackets )*/
try{
var ta=document.createElement("textarea");
ta.innerHTML=str;
return ta.value;
}catch(e){};
/*Internet Explorer*/
try{
var d=document.createElement("div");
d.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
if(typeof d.innerText!="undefined")return d.innerText;/*Sadly this strips tags as well*/
}catch(e){}
	}
	
};

var ImageGalleryPopUp = {
	largeImagesArr: '',
	thumbnailImagesArr: '',
	index:0,
	
	// This method should be called before calling any methods in this object; This populates the Product Zoom popup with images
	// from the list
	init:function() {
		this.largeImagesArr = eval(dojo.byId('fullImageAttachments').innerHTML);
		this.thumbnailImagesArr = eval(dojo.byId('thumbnailAttachments').innerHTML);
		
		
	},
	// This method return the number of images in the list
	getSize:function() {
		return this.largeImagesArr.length;
	},
	// This method will change the large image based on which thumbnail is selected
	changeImage:function(id) {
		var li = dojo.query('#thumbnailImagesRowP  > li');
		dojo.forEach(li, function(item) {
		    dojo.removeClass(item,'active');
		});
		dojo.addClass(dojo.byId(id), 'active');
		var largeImageIndex = id.split('_')[1];

		var imgURL = ImageGallery.decodeImageUrl(this.largeImagesArr[largeImageIndex]);
		imgURL = "https://tggucmcons.thegoodguys.com.au/cons"+imgURL;
		var smImgURL = imgURL;
		imgURL = smImgURL.replace('FullImage','ZoomImage');
		
	
		var movie = MagicTouch_getFlashMovieObject('mtObj0');
		if (movie.changeImage) {
		  movie.changeImage(smImgURL,imgURL);
		}

	
		//this.index = largeImageIndex;
	},
	// This method shows the popup
	showPopup:function() {
		this.init();
		hideIE6dropdown();
		dojo.byId('overlayBackground').style.display = 'block';
		dojo.byId('productZoomWrapper').style.display = 'block';
		var yOffset = self.pageYOffset;
		var availableHeight = window.innerHeight;
		var availableWidth = window.innerWidth;
		var zoomWidth = dojo.byId('productZoomWrapper').offsetWidth;
		var zoomHeight = dojo.byId('productZoomWrapper').offsetHeight;
		if (!yOffset)
			yOffset=document.documentElement.scrollTop;
		if (!availableHeight)
			availableHeight = document.documentElement.clientHeight;
		if (!availableWidth)
			availableWidth = document.documentElement.clientWidth;
			
		var topPos = availableHeight/2-zoomHeight/2+yOffset;
		if (topPos < 0)
			topPos = 0;
		var leftPos = availableWidth/2-zoomWidth/2;
		dojo.byId('productZoomWrapper').style.position = 'absolute';
		dojo.byId('productZoomWrapper').style.top = topPos+"px";
		dojo.byId('productZoomWrapper').style.left = leftPos+"px";
		//coremetrics tag
		var parentProductArray = eval(dojo.byId('parentProductPrice').innerHTML);
		var productName = parentProductArray[0].productName;
		cmCreatePageviewTag("Product Zoom:"+productName, null, null, null, storeId);
	},
	// This method hides the popup
	hidePopup:function() {
		showIE6dropdown();
		dojo.byId('productZoomWrapper').style.display = 'none';
		dojo.byId('overlayBackground').style.display = 'none';
	}
};

var EmailAFriend = {
	openEmailFriendDialog:function() {
		var form = document.getElementById('emailFriend_Form');
		form.reset(); // Reset the form while opening the popup
		var element = dojo.byId('emailFriendInner');
		if(element != null) {
			hideIE6dropdown();
			// makes the background black while opening the dialog
			dojo.byId('overlayBackground').style.display = 'block';
			// Opens the dialog
			element.style.display = 'block';
			// coremetrics tag
			cmCreatePageviewTag("Share", null, null, null, storeId);
		}
	},
	closeDialog:function() {
		var element = dojo.byId('emailFriendInner');
		if(element != null) {
			showIE6dropdown();
			// closes the dialog
			element.style.display = 'none';
			// hides the black background while closing the dialog
			dojo.byId('overlayBackground').style.display = 'none';
		}
	},
	validateAndSubmit:function() {
		var errorMessageList = new Array();
		var form = document.getElementById('emailFriend_Form');
		var name = dojo.trim(form.friend_name.value);
		var fromEmailId = dojo.trim(form.own_email.value);
		var friendsEmailIds = dojo.trim(form.friend_email_address.value);
		var message = dojo.trim(form.email_message.value);
		var captcha = dojo.trim(form.simplecaptcha_response_field.value);
		
		reWhiteSpace = new RegExp(/^\s+$/);
		reWhiteSpaceTest = new RegExp("[^a-zA-Z0-9]");
		/*reWhiteSpaceEmail = new RegExp("[^a-zA-Z0-9@.]");*/
		if(reWhiteSpaceTest.test(name) || name == '') {
			errorMessageList[MessageHelper.messages['INVALID_NAME']] = form.friend_name.id;
		}
		if(fromEmailId != null && fromEmailId != '') {
			if(!MessageHelper.isValidEmail(fromEmailId)) {
				errorMessageList[MessageHelper.messages['INVALID_FROM_EMAIL']] = form.own_email.id;
			}
		} else {
			errorMessageList[MessageHelper.messages['EMPTY_FROM_EMAIL_ID']] = form.own_email.id;
		}
		if(friendsEmailIds != null && friendsEmailIds != '') {
			if(friendsEmailIds.split(';').length > 4) {
				errorMessageList[MessageHelper.messages['INVALID_TO_EMAIL_ID_COUNT']] = form.friend_email_address.id;
			} else {
				var friendEmailArr = friendsEmailIds.split(';');
				dojo.forEach(friendEmailArr, function(friendEmail) {
					if(!MessageHelper.isValidEmail(friendEmail)) {
						errorMessageList[MessageHelper.messages['INVALID_TO_EMAIL_ID']] = form.friend_email_address.id;
					}
				});
			}
		} else {
			errorMessageList[MessageHelper.messages['EMPTY_FRIEND_EMAIL_ID']] = form.friend_email_address.id;
		}
		
		/* Added to prevent special characters in message field */
		if(reWhiteSpaceTest.test(message) || message == '') {
			errorMessageList[MessageHelper.messages['INVALID_NAME']] = form.friend_name.id;
		}
		
		if(captcha == '') {
			errorMessageList[MessageHelper.messages['TGG_EMAIL_A_FRIEND_EMPTY_CAPTCHA']] = form.simplecaptcha_response_field.id;
		}
		
		var count = 0;
		var errArr = new Array();
		var idArr = new Array();
		var firstElem = null;
		
		Util.hidePageErrorMsgs();

		for(i in errorMessageList) {
			errArr.push(i);
			if(errArr.length ==1) {
				firstElem = errorMessageList[i];
			}
			//idArr.push(errors[i]);
			count++;
			dojo.addClass(errorMessageList[i], "fn_valid_mandatory error");
			var errorDiv = dojo.create("div",{innerHTML:i},errorMessageList[i],"after");
			dojo.attr(errorDiv, {"class": "inlineError"});
		}
		if(count>0) {
			dojo.byId(firstElem).focus();
			return;
		}
		
		var emailFriendService = wc.service.getServiceById('TGGAjaxProductShare');
		emailFriendService.formId = 'emailFriend_Form';
		wc.service.invoke('TGGAjaxProductShare');
	}
	
};
//Billing&Payment Page - Billing and Payment Address Change
var AddressChange = {
	// This function is to populate the BillingDetail fields, as the user changes the address Identifier in the DropDown
	changeAddressBilling:function(form){
		var w = form.billing_use_existing.selectedIndex;
		var selectedText = form.billing_use_existing.options[w].text;
		var selectedValue = form.billing_use_existing.value;
		
		var billPickSelect = form.billing_pickup_radio;
		var billPickVal = null;
		if(billPickSelect!=null){
			var billPickChecked = false;
			dojo.forEach(billPickSelect, function(billPickEntry) {
				if(billPickEntry.checked) {
					billPickChecked = true;
					billPickVal = dojo.trim(billPickEntry.value);
				}
			});	
		}
		
		if(selectedValue == 'select_b'){
			this.newBilling(form);
			if(billPickVal == 'S' || billPickVal == 'D'){
				this.sameAsAbove(form);
			}
			return;
		}
		var addressArr = eval(dojo.byId('addressSelect').innerHTML);
		dojo.forEach(addressArr, function(address) {
   			 if(address.identifier == selectedText && address.addressType != 'Shipping' ) {
	       		form.billing_address_identifier.value = address.identifier;
		     	form.billing_title.value = address.title;
		     	form.billing_first_name.value = address.firstName;
		     	form.billing_last_name.value = address.lastName;
		     	form.address1.value = address.address1;
		     	form.address2.value = address.address2;
		     	form.city.value = address.suburb;
		     	form.state.value = address.state;
		     	form.zipCode.value = address.postcode;
		     	form.country.value = address.country;
		     	form.personal_info_phone_number.value = address.phoneNumber;
		     	form.billing_phone_number.value = address.aPhoneNumber;
		     	form.billing_email_address.value = address.email1;
	   		 } 
		});
		if(billPickVal == 'S' || billPickVal == 'D'){
			this.sameAsAbove(form);
		}
		
	},
	// This function is to populate the PickUpDetail fields, as the user changes the address Identifier in the DropDown
	changeAddressPickUp:function(form){
		var w = form.billing_pickup_use_existing.selectedIndex;
		var selectedText = form.billing_pickup_use_existing.options[w].text;
		var selectedValue = form.billing_pickup_use_existing.value;
		if(selectedValue == 'select_p'){
			this.newPickUp(form);
			return;
		}
		var addressArr = eval(dojo.byId('addressSelect').innerHTML);
		dojo.forEach(addressArr, function(address) {
   			 if(address.identifier == selectedText && address.addressType != 'Billing' ) {
	       		form.billing_pickup_address_identifier.value = address.identifier;
		     	form.billing_pickup_title.value = address.title;
		     	form.billing_pickup_first_name.value = address.firstName;
		     	form.billing_pickup_last_name.value = address.lastName;
		     	form.billing_pickup_address_1.value = address.address1;
		     	form.billing_pickup_address_2.value = address.address2;
		     	form.billing_pickup_suburb.value = address.suburb;
		     	form.billing_pickup_postcode.value = address.postcode;
		     	form.billing_pickup_state.value = address.state;
		     	form.billing_pickup_country.value = address.country;
		     	form.billing_pickup_phone_number.value = address.aPhoneNumber;
		     	form.billing_pickup_email_address.value = address.email1;
	   		 } 
		});
		
	},
	// This function is to empty the BillingDetail fields,that allows the user to enter new Details
	newBilling:function(form){
	     if(form.billing_use_existing.value == 'select_b'){
	     	form.billing_address_identifier.value = '';
	     	form.billing_title.value = 'Mr';
	     	form.billing_first_name.value = '';
	     	form.billing_last_name.value = '';
	     	form.address1.value = '';
	     	form.address2.value = '';
	     	form.city.value = '';
	     	form.state.value = '';
	     	form.zipCode.value = '';
	     	form.country.value = 'AUS';
	     	form.personal_info_phone_number.value = '';
	     	form.billing_phone_number.value = '';
	     	form.billing_email_address.value = '';
	     }
	 },
	 // This function is to empty the PickUpDetail fields,that allows the user to enter new Details
	 newPickUp:function(form){
	     if(form.billing_pickup_use_existing.value == 'select_p'){
	     	form.billing_pickup_radio.value = 'O';
	     	form.billing_pickup_address_identifier.value = '';
	     	form.billing_pickup_title.value = 'Mr';
	     	form.billing_pickup_first_name.value = '';
	     	form.billing_pickup_last_name.value = '';
	     	form.billing_pickup_phone_number.value = '';
	     	form.billing_pickup_email_address.value = '';
	     	form.billing_pickup_address_1.value = '';
	     	form.billing_pickup_address_2.value = '';
	     	form.billing_pickup_suburb.value = '';
	     	form.billing_pickup_postcode.value = '';
	     	form.billing_pickup_state.value = '';
	     	form.billing_pickup_country.value = 'AUS';
	     }
	  },
	  //This function re-fills in the BillingDetails in the PickUpDetail fields
	  sameAsAbove:function(form){ 
	  	var addrss = form.billing_pickup_radio;
		var checkedValue;
		if(addrss!=null){
			dojo.forEach(addrss, function(optValue) {
				if(optValue.checked) {
					checkedValue = dojo.trim(optValue.value);
				}
			});
		}
	    if(checkedValue == 'S' || checkedValue == 'D'){
	     	form.billing_pickup_use_existing.value = 'select_p';
	     	form.billing_pickup_address_identifier.value = form.billing_address_identifier.value;
	     	form.billing_pickup_title.value = form.billing_title.value;
	     	form.billing_pickup_first_name.value = form.billing_first_name.value;
	     	form.billing_pickup_last_name.value = form.billing_last_name.value;
	     	form.billing_pickup_address_1.value = form.address1.value;
	     	form.billing_pickup_address_2.value = form.address2.value;
	     	form.billing_pickup_suburb.value = form.city.value;
	     	form.billing_pickup_postcode.value = form.zipCode.value;
	     	form.billing_pickup_state.value = form.state.value;
	     	form.billing_pickup_country.value = form.country.value;
	     	form.billing_pickup_phone_number.value = form.billing_phone_number.value;
	     	form.billing_pickup_email_address.value = form.billing_email_address.value;
	  		}
	  },   
	  //This function is to empty the  PickUpDetail Fields, if the user select the 'Other' option.
	  other:function(form){ 
	  	var addrss = form.billing_pickup_radio;
		var checkedValue;
		if(addrss!=null){
			dojo.forEach(addrss, function(optValue) {
				if(optValue.checked) {
					checkedValue = dojo.trim(optValue.value);
				}
			});
		}
	    if(checkedValue == 'O'){
	    	form.billing_pickup_use_existing.value = 'select_p';
	     	this.newPickUp(form);
			return;
	  		}
	  }   

};

var orderPrepare = {

	formValidate:function(form){
		reWhiteSpace = new RegExp(/^\s+$/);
	    var errors = new Object(); 
	    var errors1 = new Object();
	    var validchars = "abcdefghijklmnopqrstuvwxyz0123456789 /\\-'";
	    var validnicknamechars = "abcdefghijklmnopqrstuvwxyz0123456789 /\\-'&_@!#$%^&*()=+`~{}[]|,.";
	    var validnums = "0123456789- ";
	    var validnumber = "0123456789";
	    var validanum = "abcdefghijklmnopqrstuvwxyz0123456789";
	    Util.hidePageErrorMsgs();
	    
		if(form.billing_address_identifier != null && reWhiteSpace.test(form.billing_address_identifier.value) || form.billing_address_identifier.value == ""){
			errors[MessageHelper.messages["TGG_ADDRESS_IDENTIFIER_EMPTY"]]= form.billing_address_identifier.id;
		}else if(form.billing_address_identifier != null) {
			for (var i=0; i < form.billing_address_identifier.value.length; i++) {
				var letter = form.billing_address_identifier.value.charAt(i).toLowerCase();
				if (validnicknamechars.indexOf(letter) == -1){
					errors[MessageHelper.messages["TGG_ADDRESS_IDENTIFIER_INVALID"]]= form.billing_address_identifier.id;
					break;
				}
			}
			if(dojo.trim(form.billing_address_identifier.value).length < 3){
				errors[MessageHelper.messages["ERR_MINIMUMLENGTH_NICKNAME"]] = form.billing_address_identifier.id;
			}
		}
		
		if(form.billing_first_name != null && reWhiteSpace.test(form.billing_first_name.value) || form.billing_first_name.value == ""){
			errors[MessageHelper.messages["TGG_FIRST_NAME_EMPTY"]]= form.billing_first_name.id;
		}else if(form.billing_first_name != null){
			if(form.billing_first_name.value.length >= 30) {
				errors[MessageHelper.messages["TGG_FIRST_NAME_TOO_LONG"]]= form.billing_first_name.id;
			} else {
				for (var i=0; i < form.billing_first_name.value.length; i++) {
					var letter = form.billing_first_name.value.charAt(i).toLowerCase();
					if (validchars.indexOf(letter) == -1){
						errors[MessageHelper.messages["TGG_FIRST_NAME_INVALID"]]= form.billing_first_name.id;
						break;
					}
				}
			}
		}
		
		if(form.billing_last_name != null && reWhiteSpace.test(form.billing_last_name.value) || form.billing_last_name.value == ""){
			errors[MessageHelper.messages["TGG_LAST_NAME_EMPTY"]]= form.billing_last_name.id;
		}else if(form.billing_last_name != null){
			if(form.billing_last_name.value.length >= 30) {
				errors[MessageHelper.messages["TGG_LAST_NAME_TOO_LONG"]]= form.billing_last_name.id;
			} else if(form.billing_last_name.value.length < 2) {
				errors[MessageHelper.messages["TGG_LAST_NAME_MIN_LENGTH_ERROR"]]= form.billing_last_name.id;
			} else {
				for (var i=0; i < form.billing_last_name.value.length; i++) {
					var letter = form.billing_last_name.value.charAt(i).toLowerCase();
					if (validchars.indexOf(letter) == -1){
						errors[MessageHelper.messages["TGG_LAST_NAME_INVALID"]]= form.billing_last_name.id;
						break;
					}
				}
			}
		}
		
		if(form.address1 != null && reWhiteSpace.test(form.address1.value) || form.address1.value == ""){
			dojo.addClass(form.address1.id, "fn_valid_mandatory error");
			dojo.addClass(form.address2.id, "fn_valid_mandatory error");
			errors[MessageHelper.messages["TGG_STREET_ADDRESS_EMPTY"]]= dojo.byId('billing_address_street');
		}else if(form.address1 != null){
			var validcharsA = "abcdefghijklmnopqrstuvwxyz0123456789 /\\-',.:;[]()&*";
			for (var i=0; i < form.address1.value.length; i++) {
				var letter = form.address1.value.charAt(i).toLowerCase();
				if (validcharsA.indexOf(letter) == -1){
					dojo.addClass(form.address1.id, "fn_valid_mandatory error");
					dojo.addClass(form.address2.id, "fn_valid_mandatory error");
					errors[MessageHelper.messages["TGG_STREET_ADDRESS_INVALID"]]= dojo.byId('billing_address_street');
					break;
				}
			}
			if(form.address2 != null && form.address2.value != ''){
				for (var i=0; i < form.address2.value.length; i++) {
					var letter = form.address2.value.charAt(i).toLowerCase();
					if (validcharsA.indexOf(letter) == -1){
						dojo.addClass(form.address1.id, "fn_valid_mandatory error");
						dojo.addClass(form.address2.id, "fn_valid_mandatory error");
						errors[MessageHelper.messages["TGG_STREET_ADDRESS_INVALID"]]= dojo.byId('billing_address_street');
						break;
					}
				}
			}
		}
		
		if(form.city != null && reWhiteSpace.test(form.city.value) || form.city.value == ""){
			errors[MessageHelper.messages["TGG_SUBURB_EMPTY"]]= form.city.id;
		}else if(form.city != null){
			for (var i=0; i < form.city.value.length; i++) {
				var letter = form.city.value.charAt(i).toLowerCase();
				if (validchars.indexOf(letter) == -1){
					errors[MessageHelper.messages["TGG_SUBURB_INVALID"]]= form.city.id;
					break;
				}
			}
		}
			
		if(form.zipCode != null && reWhiteSpace.test(form.zipCode.value) || form.zipCode.value == ""){
			errors[MessageHelper.messages["TGG_POSTCODE_EMPTY"]]= form.zipCode.id;
		}else if(form.zipCode != null){
			if(form.zipCode.value.length > 8) {
				errors[MessageHelper.messages["TGG_POSTCODE_INVALID"]]= form.zipCode.id;
			} else {
				for (var i=0; i < form.zipCode.value.length; i++) {
					var letter = form.zipCode.value.charAt(i).toLowerCase();
					if (validnums.indexOf(letter) == -1){
						errors[MessageHelper.messages["TGG_POSTCODE_INVALID"]]= form.zipCode.id;
						break;
					}
				}
			}
		}
		
		if(form.state != null && reWhiteSpace.test(form.state.value) || form.state.value == ""){
			errors[MessageHelper.messages["TGG_STATE_EMPTY"]]= form.state.id;
		}
		
		if(form.country != null && reWhiteSpace.test(form.country.value) || form.country.value == ""){
			errors[MessageHelper.messages["TGG_COUNTRY_EMPTY"]]= form.country.id;
		}
		
		if(form.billing_phone_number != null && dojo.trim(form.billing_phone_number.value) == "" ){
			dojo.addClass(form.billing_phone_number.id, "fn_valid_mandatory error");
			errors[MessageHelper.messages["TGG_PHONE_NUMBER_EMPTY"]]= form.billing_phone_number.id;
		}else if(dojo.trim(form.billing_phone_number.value) != "" ){
			for (var i=0; i < form.billing_phone_number.value.length; i++) {
				var letter = form.billing_phone_number.value.charAt(i).toLowerCase();
				if (validnums.indexOf(letter) == -1){
					dojo.addClass(form.billing_phone_number.id, "fn_valid_mandatory error");
					errors[MessageHelper.messages["TGG_PHONE_NUMBER_INVALID"]]= form.billing_phone_number.id;
					break;
				}
			}
		}
		
		if(form.billing_email_address != null && reWhiteSpace.test(form.billing_email_address.value) || form.billing_email_address.value == ""){
			errors[MessageHelper.messages["TGG_EMAIL_ADDRESS_EMPTY"]]= form.billing_email_address.id;
		}else if(!MessageHelper.isValidEmail(form.billing_email_address.value)){
			errors[MessageHelper.messages["TGG_EMAIL_ADDRESS_INVALID"]]= form.billing_email_address.id;
		}
		
		if(form.billing_email_address != null && form.billing_email_address.value != null && form.billing_email_address.value != ""){
			form.billing_email_address.value = form.billing_email_address.value.toLowerCase();
		}
		
		var billPickSelect = form.billing_pickup_radio;
		var billPickVal = null;
		if(billPickSelect!=null){
			var billPickChecked = false;
			dojo.forEach(billPickSelect, function(billPickEntry) {
				if(billPickEntry.checked) {
					billPickChecked = true;
					billPickVal = dojo.trim(billPickEntry.value);
					if(billPickVal == 'S'){
						AddressChange.sameAsAbove(form);
					}
				}
			});	
		}
		if(!billPickChecked){
			errors[MessageHelper.messages["TGG_BILLING_PICKUP_RADIO_EMPTY"]]= "tempBillingPickupSelectionDiv";
		}else if(billPickVal!=null && billPickVal!='S'){
			if(form.billing_pickup_address_identifier != null && reWhiteSpace.test(form.billing_pickup_address_identifier.value) || form.billing_pickup_address_identifier.value == ""){
				errors1[MessageHelper.messages["TGG_ADDRESS_IDENTIFIER_EMPTY"]]= form.billing_pickup_address_identifier.id;
			}else if(form.billing_pickup_address_identifier != null){
				for (var i=0; i < form.billing_pickup_address_identifier.value.length; i++) {
					var letter = form.billing_pickup_address_identifier.value.charAt(i).toLowerCase();
					if (validchars.indexOf(letter) == -1){
						errors1[MessageHelper.messages["TGG_ADDRESS_IDENTIFIER_INVALID"]]= form.billing_pickup_address_identifier.id;
						break;
					}
				}
				if(dojo.trim(form.billing_pickup_address_identifier.value).length < 3){
					errors1[MessageHelper.messages["ERR_MINIMUMLENGTH_NICKNAME"]] = form.billing_pickup_address_identifier.id;
				}
			}
			if(form.billing_pickup_first_name != null && reWhiteSpace.test(form.billing_pickup_first_name.value) || form.billing_pickup_first_name.value == ""){
				errors1[MessageHelper.messages["TGG_FIRST_NAME_EMPTY"]]= form.billing_pickup_first_name.id;
			}else if(form.billing_pickup_first_name != null){
				for (var i=0; i < form.billing_pickup_first_name.value.length; i++) {
					var letter = form.billing_pickup_first_name.value.charAt(i).toLowerCase();
					if (validchars.indexOf(letter) == -1){
						errors1[MessageHelper.messages["TGG_FIRST_NAME_INVALID"]]= form.billing_pickup_first_name.id;
						break;
					}
				}
			}
			
			if(form.billing_pickup_last_name != null && reWhiteSpace.test(form.billing_pickup_last_name.value) || form.billing_pickup_last_name.value == ""){
				errors1[MessageHelper.messages["TGG_LAST_NAME_EMPTY"]]= form.billing_pickup_last_name.id;
			} else if(form.billing_pickup_last_name != null){
				if(form.billing_pickup_last_name.value.length >= 30) {
					errors1[MessageHelper.messages["TGG_LAST_NAME_TOO_LONG"]]= form.billing_pickup_last_name.id;
				} else if(form.billing_pickup_last_name.value.length < 2) {
					errors1[MessageHelper.messages["TGG_LAST_NAME_MIN_LENGTH_ERROR"]]= form.billing_pickup_last_name.id;
				} else {
					for (var i=0; i < form.billing_pickup_last_name.value.length; i++) {
						var letter = form.billing_pickup_last_name.value.charAt(i).toLowerCase();
						if (validchars.indexOf(letter) == -1){
							errors1[MessageHelper.messages["TGG_LAST_NAME_INVALID"]]= form.billing_pickup_last_name.id;
							break;
						}
					}
				}
			}
			
			if(form.billing_pickup_address_1 != null && reWhiteSpace.test(form.billing_pickup_address_1.value) || form.billing_pickup_address_1.value == ""){
				dojo.addClass(form.billing_pickup_address_1.id, "fn_valid_mandatory error");
				dojo.addClass(form.billing_pickup_address_2.id, "fn_valid_mandatory error");
				errors1[MessageHelper.messages["TGG_STREET_ADDRESS_EMPTY"]]= dojo.byId('billing_pickup_address_street');
			}else if(form.billing_pickup_address_1 != null){
				var validcharsA = "abcdefghijklmnopqrstuvwxyz0123456789 /\\-',.:;[]()&*";
				for (var i=0; i < form.billing_pickup_address_1.value.length; i++) {
					var letter = form.billing_pickup_address_1.value.charAt(i).toLowerCase();
					if (validcharsA.indexOf(letter) == -1){
						dojo.addClass(form.billing_pickup_address_1.id, "fn_valid_mandatory error");
						dojo.addClass(form.billing_pickup_address_2.id, "fn_valid_mandatory error");
						errors1[MessageHelper.messages["TGG_STREET_ADDRESS_INVALID"]]= dojo.byId('billing_pickup_address_street');
						break;
					}
				}
				if(form.billing_pickup_address_2 != null && form.billing_pickup_address_2.value != ''){
					for (var i=0; i < form.billing_pickup_address_2.value.length; i++) {
						var letter = form.billing_pickup_address_2.value.charAt(i).toLowerCase();
						if (validcharsA.indexOf(letter) == -1){
							dojo.addClass(form.billing_pickup_address_1.id, "fn_valid_mandatory error");
							dojo.addClass(form.billing_pickup_address_2.id, "fn_valid_mandatory error");
							errors1[MessageHelper.messages["TGG_STREET_ADDRESS_INVALID"]]= dojo.byId('billing_pickup_address_street');
							break;
						}
					}
				}
			}
			
			if(form.billing_pickup_suburb != null && reWhiteSpace.test(form.billing_pickup_suburb.value) || form.billing_pickup_suburb.value == ""){
				errors1[MessageHelper.messages["TGG_SUBURB_EMPTY"]]= form.billing_pickup_suburb.id;
			}else if(form.billing_pickup_suburb != null){
				for (var i=0; i < form.billing_pickup_suburb.value.length; i++) {
					var letter = form.billing_pickup_suburb.value.charAt(i).toLowerCase();
					if (validchars.indexOf(letter) == -1){
						errors1[MessageHelper.messages["TGG_SUBURB_INVALID"]]= form.billing_pickup_suburb.id;
						break;
					}
				}
			}
				
			if(form.billing_pickup_postcode != null && reWhiteSpace.test(form.billing_pickup_postcode.value) || form.billing_pickup_postcode.value == ""){
				errors1[MessageHelper.messages["TGG_POSTCODE_EMPTY"]]= form.billing_pickup_postcode.id;
			}else if(form.billing_pickup_postcode != null){
				if(form.billing_pickup_postcode.value.length > 8) {
					errors1[MessageHelper.messages["TGG_POSTCODE_INVALID"]]= form.billing_pickup_postcode.id;
				} else {
					for (var i=0; i < form.billing_pickup_postcode.value.length; i++) {
						var letter = form.billing_pickup_postcode.value.charAt(i).toLowerCase();
						if (validnums.indexOf(letter) == -1){
							errors1[MessageHelper.messages["TGG_POSTCODE_INVALID"]]= form.billing_pickup_postcode.id;
							break;
						}
					}
				}
			}
			
			if(form.billing_pickup_state != null && reWhiteSpace.test(form.billing_pickup_state.value) || form.billing_pickup_state.value == ""){
				errors1[MessageHelper.messages["TGG_STATE_EMPTY"]]= form.billing_pickup_state.id;
			}
			
			if(form.billing_pickup_country != null && reWhiteSpace.test(form.billing_pickup_country.value) || form.billing_pickup_country.value == ""){
				errors1[MessageHelper.messages["TGG_COUNTRY_EMPTY"]]= form.billing_pickup_country.id;
			}
		
			
			if(form.billing_pickup_phone_number != null && dojo.trim(form.billing_pickup_phone_number.value) == "" ){
				dojo.addClass(form.billing_pickup_phone_number.id, "fn_valid_mandatory error");
				errors1[MessageHelper.messages["TGG_PHONE_NUMBER_EMPTY"]]= form.billing_pickup_phone_number.id;
			}else if(dojo.trim(form.billing_pickup_phone_number.value) != "" ){
				for (var i=0; i < form.billing_pickup_phone_number.value.length; i++) {
					var letter = form.billing_pickup_phone_number.value.charAt(i).toLowerCase();
					if (validnums.indexOf(letter) == -1){
						dojo.addClass(form.billing_pickup_phone_number.id, "fn_valid_mandatory error");
						errors1[MessageHelper.messages["TGG_PHONE_NUMBER_INVALID"]]= form.billing_pickup_phone_number.id;
						break;
					}
				}		
			}
			
			if(form.billing_pickup_email_address != null && reWhiteSpace.test(form.billing_pickup_email_address.value) || form.billing_pickup_email_address.value == ""){
				errors1[MessageHelper.messages["TGG_EMAIL_ADDRESS_EMPTY"]]= form.billing_pickup_email_address.id;
			}else if(!MessageHelper.isValidEmail(form.billing_pickup_email_address.value)){
				errors1[MessageHelper.messages["TGG_EMAIL_ADDRESS_INVALID"]]= form.billing_pickup_email_address.id;
			}
			
			if(form.billing_pickup_email_address != null && form.billing_pickup_email_address.value != null && form.billing_pickup_email_address.value != ""){
				form.billing_pickup_email_address.value = form.billing_pickup_email_address.value.toLowerCase();
			}
		}
		
		var count = 0;
		var errArr = new Array();
		var idArr = new Array();
		var firstElem = null;
		
		for(i in errors) {
			errArr.push(i);
			if(errArr.length ==1) {
				firstElem = errors[i];
			}
			//idArr.push(errors[i]);
			count++;
			dojo.addClass(errors[i], "fn_valid_mandatory error");
			if(errors[i] == "tempBillingPickupSelectionDiv"){
				var errorDiv = dojo.create("div",{innerHTML:'<font color = "#a9000c">'+i+'</font>'},errors[i],"after");
			}else{
				var errorDiv = dojo.create("div",{innerHTML:i},errors[i],"after");
			}
			dojo.attr(errorDiv, {"class": "inlineError"});
		}
		if(billPickChecked){
			for(i in errors1) {
				errArr.push(i);
				if(firstElem == null) {
					firstElem = errors1[i];
				}
				count++;
				dojo.addClass(errors1[i], "fn_valid_mandatory error");
				var errorDiv = dojo.create("div",{innerHTML:i},errors1[i],"after");
				dojo.attr(errorDiv, {"class": "inlineError"});
			}
		}
		if(count>0) {
			dojo.byId(firstElem).focus();
			return;
		} else {
			this.QASValidate(form);
		}
	},
	
	QASValidate:function(form){
		var params = [];
		params["address1"] = dojo.trim(form.address1.value);
		params["address2"] = dojo.trim(form.address2.value);
		params["suburb"] = dojo.trim(form.city.value);
		params["postcode"] = dojo.trim(form.zipCode.value);
		params["state"] = dojo.trim(form.state.value);
		params["country"] = dojo.trim(form.country.value);
		cursor_wait();
		MyAccountUtil.validateAddressByQAS("AjaxQASAddressValidate",params,"Billing_PickUp_Payment","billing","");	
	}
};

var GiftCardService = {
	getCardBalance:function(giftCardBalanceURL) {
		var errorMessageList = new Array();
		
		var frm = dojo.byId('shopping_cart_Form');
		if(frm !=null){
			giftCardNum = frm.gift_card_number.value;
			giftCardType = frm.gift_card_type.options[frm.gift_card_type.selectedIndex].value;
			giftCardPin = frm.gift_card_pin.value;
			orderId = frm.orderId.value;
		}
		giftCardNum = dojo.trim(giftCardNum);
		giftCardPin = dojo.trim(giftCardPin);
		
		if(giftCardType == null || giftCardType == "") {
			errorMessageList[MessageHelper.messages['TGG_CARD_TYPE_EMPTY']] = frm.gift_card_type.id;
		}
		if(giftCardNum == null ||  giftCardNum == "") {
			errorMessageList[MessageHelper.messages['TGG_CARD_NUMBER_EMPTY']] = frm.gift_card_number.id;
		}
		if((giftCardPin == null || giftCardPin == "") && !(giftCardType == "POSGiftCard")) {
			errorMessageList[MessageHelper.messages['TGG_PIN_EMPTY']] = frm.gift_card_pin.id;
		}
		
		var count = 0;
		var errArr = new Array();
		var idArr = new Array();
		var firstElem = null;
		
		Util.hidePageErrorMsgs();

		for(i in errorMessageList) {
			errArr.push(i);
			if(errArr.length ==1) {
				firstElem = errorMessageList[i];
			}
			//idArr.push(errors[i]);
			count++;
			dojo.addClass(errorMessageList[i], "fn_valid_mandatory error");
			var errorDiv = dojo.create("div",{innerHTML:i},errorMessageList[i],"after");
			dojo.attr(errorDiv, {"class": "inlineError"});
		}
		if(count>0) {
			dojo.byId(firstElem).focus();
			return;
		}
	    if( (giftCardType == "RedGiftCard"  && giftCardPin !="" ) || giftCardType == "POSGiftCard"){
 		    giftCardBalanceURL = giftCardBalanceURL + "&gcNumber="+giftCardNum+"&gcType="+giftCardType+"&gcPin="+giftCardPin+"&orderId="+orderId;
			wc.service.getServiceById("CheckGiftcardBalance").url=giftCardBalanceURL;
			wc.service.invoke("CheckGiftcardBalance");
		}	
	},
	ShowBalanceDiv:function(cardNum, cardBalance, cardMessage) {

		var cardNumElement = dojo.byId('checkBalance_cardnum');
		if(cardNumElement !=null){
			cardNumElement.innerHTML = cardNum;
		}
		var cardBalanceElement = dojo.byId('checkBalance_balance');
		if(cardBalanceElement !=null){
			cardBalanceElement.innerHTML = cardBalance;
		}

		var cardMessageElement = dojo.byId('checkBalance_message');
		if(cardMessageElement !=null){
			cardMessageElement.innerHTML = cardMessage;
		}
		
		var element = dojo.byId('balanceWrapper');
		if(element != null) {
			// makes the background black while opening the dialog
			dojo.byId('overlayBackground').style.display = 'block';
			// Opens the dialog
			element.style.display = 'block';
			dojo.byId('balanceSelection').style.display = 'block';
			dojo.byId('error').style.display = 'none';
		}
	},
	hideBalanceDiv:function() {
		var element = dojo.byId('balanceWrapper');
		if(element != null) {
			// makes the background black while opening the dialog
			dojo.byId('overlayBackground').style.display = 'none';
			// Opens the dialog
			element.style.display = 'none';
		}
	},
	showError:function(errorMessage) {
		var element = dojo.byId('balanceWrapper');
		if(element != null) {
			// makes the background black while opening the dialog
			dojo.byId('overlayBackground').style.display = 'block';
			// Opens the dialog
			element.style.display = 'block';
			dojo.byId('balanceSelection').style.display = 'none';
			dojo.byId('error').innerHTML = '<h2 style="color:red;font-weight:bold;align:center">' + errorMessage + '</h2>';
			dojo.byId('error').style.display = 'block';
		}
	}
};

var Payment = {
	cardSelect:function(form) {
		Util.hidePageErrorMsgs();
		if(form.gift_card_type.value == ''){
			form.gift_card_number.value = '';
			form.gift_card_pin.value = '';
			dojo.byId('red_card_pin').style.display = 'none';
		}
		if(form.gift_card_type.value == 'POSGiftCard'){
			form.gift_card_number.value = '';
			dojo.byId('red_card_pin').style.display = 'none';
		}
		if(form.gift_card_type.value == 'RedGiftCard'){
			form.gift_card_number.value = '';
			dojo.byId('red_card_pin').style.display = 'block';
		}
	},
	paymentMethodValidate:function(form){
		if(!document.getElementById("tcscheckbox").checked) {
			alert("The terms and conditions checkbox has not be clicked");
			return;
		}
		clearGiftCard();
		reWhiteSpace = new RegExp(/^\s+$/);
		var errors = new Object();
		var validnumber = "0123456789";
		var validAmount = "0123456789.";
	    var validanum = "abcdefghijklmnopqrstuvwxyz0123456789";
		Util.hidePageErrorMsgs();
		if(form.gift_card_type.value != ''){
			if(form.gift_card_type.value == 'POSGiftCard'){
				if(form.gift_card_number != null && reWhiteSpace.test(form.gift_card_number.value) || form.gift_card_number.value == ""){
					errors[MessageHelper.messages["TGG_CARD_NUMBER_EMPTY"]]= form.gift_card_number.id;
				}else if(form.gift_card_number != null){
					if(form.gift_card_number.value.length < 6 || form.gift_card_number.value.length > 40){
						dojo.addClass(form.gift_card_number.id, "fn_valid_mandatory error");
						errors[MessageHelper.messages["TGG_CARD_NUMBER_INVALID"]]= form.gift_card_number.id;
					}else{
						for (var i=0; i < form.gift_card_number.value.length; i++) {
							var letter = form.gift_card_number.value.charAt(i).toLowerCase();
							if (validanum.indexOf(letter) == -1){
								dojo.addClass(form.gift_card_number.id, "fn_valid_mandatory error");
								errors[MessageHelper.messages["TGG_CARD_NUMBER_INVALID"]]= form.gift_card_number.id;
								break;
							}
						}
					}
				}
				if(form.gift_card_amount != null && reWhiteSpace.test(form.gift_card_amount.value) || form.gift_card_amount.value == ""){
					errors[MessageHelper.messages["TGG_AMOUNT_EMPTY"]]= form.gift_card_amount.id;
				}else if(form.gift_card_amount != ''){
					for (var i=0; i < form.gift_card_amount.value.length; i++) {
						var letter = form.gift_card_amount.value.charAt(i).toLowerCase();
						if (validAmount.indexOf(letter) == -1){
							dojo.addClass(form.gift_card_amount.id, "fn_valid_mandatory error");
							errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]= form.gift_card_amount.id;
							break;
						}
					}
					if(errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]!= form.gift_card_amount.id){
						if(eval(form.gift_card_amount.value) > eval(form.grandTotal.value)){
							dojo.addClass(form.gift_card_amount.id, "fn_valid_mandatory error");
							errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]= form.gift_card_amount.id;
						}
					}
				}
			}else if(form.gift_card_type.value == 'RedGiftCard'){
				if(form.gift_card_number != null && reWhiteSpace.test(form.gift_card_number.value) || form.gift_card_number.value == ""){
					dojo.addClass(form.gift_card_number.id, "fn_valid_mandatory error");
					errors[MessageHelper.messages["TGG_CARD_NUMBER_EMPTY"]]= form.gift_card_number.id;
				}else if(form.gift_card_number != null){
					if(form.gift_card_number.value.length < 6 || form.gift_card_number.value.length > 17){
						dojo.addClass(form.gift_card_number.id, "fn_valid_mandatory error");
						errors[MessageHelper.messages["TGG_CARD_NUMBER_INVALID"]]= form.gift_card_number.id;
					}else{
						for (var i=0; i < form.gift_card_number.value.length; i++) {
							var letter = form.gift_card_number.value.charAt(i).toLowerCase();
							if (validnumber.indexOf(letter) == -1){
								dojo.addClass(form.gift_card_number.id, "fn_valid_mandatory error");
								errors[MessageHelper.messages["TGG_CARD_NUMBER_INVALID"]]= form.gift_card_number.id;
								break;
							}
						}
					}
				}
				if(form.gift_card_pin != null && reWhiteSpace.test(form.gift_card_pin.value) || form.gift_card_pin.value == ""){
					dojo.addClass(form.gift_card_pin.id, "fn_valid_mandatory error");
					errors[MessageHelper.messages["TGG_PIN_EMPTY"]]= form.gift_card_pin.id;
				}else if(form.gift_card_pin != ''){
					if(form.gift_card_pin.value.length != 4){
						dojo.addClass(form.gift_card_pin.id, "fn_valid_mandatory error");
						errors[MessageHelper.messages["TGG_PIN_INVALID"]]= form.gift_card_pin.id;
					}else{
						for (var i=0; i < form.gift_card_pin.value.length; i++) {
							var letter = form.gift_card_pin.value.charAt(i).toLowerCase();
							if (validnumber.indexOf(letter) == -1){
								dojo.addClass(form.gift_card_pin.id, "fn_valid_mandatory error");
								errors[MessageHelper.messages["TGG_PIN_INVALID"]]= form.gift_card_pin.id;
								break;
							}
						}
					}
				}	
				if(form.gift_card_amount != null && reWhiteSpace.test(form.gift_card_amount.value) || form.gift_card_amount.value == ""){
					errors[MessageHelper.messages["TGG_AMOUNT_EMPTY"]]= form.gift_card_amount.id;
				}else if(form.gift_card_amount != ''){
					for (var i=0; i < form.gift_card_amount.value.length; i++) {
						var letter = form.gift_card_amount.value.charAt(i).toLowerCase();
						if (validAmount.indexOf(letter) == -1){
							dojo.addClass(form.gift_card_amount.id, "fn_valid_mandatory error");
							errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]= form.gift_card_amount.id;
							break;
						}
					}
					if(errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]!= form.gift_card_amount.id){
						if(eval(form.gift_card_amount.value) > eval(form.grandTotal.value)){
							dojo.addClass(form.gift_card_amount.id, "fn_valid_mandatory error");
							errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]= form.gift_card_amount.id;
						}
					}
				}
			}
		}
		var count = 0;
		var errArr = new Array();
		var idArr = new Array();
		var firstElem = null;
		
		for(i in errors) {
			errArr.push(i);
			if(errArr.length ==1) {
				firstElem = errors[i];
			}
			//idArr.push(errors[i]);
			count++;
			dojo.addClass(errors[i], "fn_valid_mandatory error");
			var errorDiv = dojo.create("div",{innerHTML:i},errors[i],"after");
			dojo.attr(errorDiv, {"class": "inlineError"});
		}
		if(count>0) {
			dojo.byId(firstElem).focus();
			return;
		} else {
			form.submit();
		}
	},
	amountCalculate:function(form) {
		reWhiteSpace = new RegExp(/^\s+$/);
		var errors = new Object(); 
		var validnums = "0123456789.";
		
		Util.hidePageErrorMsgs();
		
		if(form.gift_card_amount.value != null && dojo.trim(form.gift_card_amount.value) != '' && form.grandTotal.value != null && form.gift_card_type.value != ''){
			if(form.gift_card_amount != null && reWhiteSpace.test(form.gift_card_amount.value) || form.gift_card_amount.value == ""){
				dojo.addClass(form.gift_card_amount.id, "fn_valid_mandatory error");
				errors[MessageHelper.messages["TGG_AMOUNT_EMPTY"]]= form.gift_card_amount.id;
			}else if(form.gift_card_amount != ''){
				for (var i=0; i < form.gift_card_amount.value.length; i++) {
					var letter = form.gift_card_amount.value.charAt(i).toLowerCase();
					if (validnums.indexOf(letter) == -1){
						dojo.addClass(form.gift_card_amount.id, "fn_valid_mandatory error");
						errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]= form.gift_card_amount.id;
						break;
					}
				}
				if(errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]!= form.gift_card_amount.id){
					if(eval(form.gift_card_amount.value) > eval(form.grandTotal.value)){
						dojo.addClass(form.gift_card_amount.id, "fn_valid_mandatory error");
						errors[MessageHelper.messages["TGG_AMOUNT_INVALID"]]= form.gift_card_amount.id;
					}
				}
			}
			
			var count = 0;
			var errArr = new Array();
			var idArr = new Array();
			var firstElem = null;
			
			for(i in errors) {
				errArr.push(i);
				if(errArr.length ==1) {
					firstElem = errors[i];
				}
				//idArr.push(errors[i]);
				count++;
				dojo.addClass(errors[i], "fn_valid_mandatory error");
				var errorDiv = dojo.create("div",{innerHTML:i},errors[i],"after");
				dojo.attr(errorDiv, {"class": "inlineError"});
			}
			if(count>0) {
				dojo.byId(firstElem).focus();
				return;
			} else {
				dojo.byId('payment_amount').innerHTML = '$'+ dojo.number.format((eval(form.grandTotal.value) - eval(form.gift_card_amount.value)),{ places:2, pattern:'#'});
			}
		}else if(form.gift_card_amount.value != ''){
			dojo.addClass(form.gift_card_type.id, "fn_valid_mandatory error");
			errors[MessageHelper.messages["TGG_CARD_TYPE_EMPTY"]]= form.gift_card_type.id;
			for(i in errors) {
				//idArr.push(errors[i]);
				dojo.addClass(errors[i], "fn_valid_mandatory error");
				var errorDiv = dojo.create("div",{innerHTML:i},errors[i],"after");
				dojo.attr(errorDiv, {"class": "inlineError"});
			}
		}		
	}
};

var Pagination = {
	/**
	* This function is used to load the value of the controller URL.
	* @param {string} contentURL  the value of the controller URL.
	*/
	loadContentURL:function(contentURL){
		/* Handles multiple clicks */
		cursor_wait();
		var bgnIndx = contentURL.substr(contentURL.indexOf("beginIndex")+11,1);
		CommonControllersDeclarationJS.setControllerURL('ShopCartPaginationDisplayController',contentURL);		
		wc.render.updateContext('ShopCartPaginationDisplay_Context',{'beginIndex':bgnIndx});
		//wc.render.updateContext('ShopCartPaginationDisplay_Context',{'beginIndex':'<c:out value='${beginIndex - pageSize}'/>'});
	}

};


var SendUsMessage = {
	// This function is used to validate and submit the Send us Message form in the 
	// contact us page.
	validateAndSubmit:function() {
		var errorMessageList = new Object();
		var form = document.getElementById('address_Form');
		var option = dojo.trim(form.send_message_subject.value);
		var name = dojo.trim(form.send_message_name.value);
		var email = dojo.trim(form.send_message_email.value);
		var suburb = dojo.trim(form.send_message_suburb.value);
		var postCode = dojo.trim(form.send_message_postcode.value);
//Fix for Defect Id - 722 - Start
	    var validnums = "0123456789";
	    var phone = dojo.trim(form.send_message_phone_number.value);
//Fix for Defect Id - 722 - End		
		reWhiteSpace = new RegExp(/^\s+$/);
		
		if(option == 'none') {
			errorMessageList[MessageHelper.messages['OPTION_NOT_SELECTED']] = form.send_message_subject.id;
		}
		if(reWhiteSpace.test(name) || name == '') {
			errorMessageList[MessageHelper.messages['EMPTY_NAME']] = form.send_message_name.id;
		}
		if(email != null && email != '') {
			if(!MessageHelper.isValidEmail(email)) {
				errorMessageList[MessageHelper.messages['INVALID_EMAIL']] = form.send_message_email.id;
			}
		} else {
			errorMessageList[MessageHelper.messages['EMPTY_EMAIL']] = form.send_message_email.id;
		}
		if(reWhiteSpace.test(suburb) || suburb == '') {
			errorMessageList[MessageHelper.messages['EMPTY_SUBURB']] = form.send_message_suburb.id;
		} 
		if(reWhiteSpace.test(postCode) || postCode == '') {
			errorMessageList[MessageHelper.messages['EMPTY_POST_CODE']] = form.send_message_postcode.id;
//Fix for Defect Id - 722 - Start
		} else {
		//if(postCode.length > 4) {
		//	errorMessageList[MessageHelper.messages['INVALID_POST_CODE']] = form.send_message_postcode.id;			
			if (postCode.length == 4) {
				for (var i=0; i < postCode.length; i++) {
					var letter = postCode.charAt(i).toLowerCase();
					if (validnums.indexOf(letter) == -1){
						errorMessageList[MessageHelper.messages['INVALID_POST_CODE']]= form.send_message_postcode.id;
						break;
					}
				}
			} else {
				errorMessageList[MessageHelper.messages['INVALID_POST_CODE']]= form.send_message_postcode.id;
			}
		}

		if(reWhiteSpace.test(phone) || phone == '') {
			//errorMessageList[MessageHelper.messages['INVALID_PHONE_NUMBER']] = form.send_message_phone_number.id;
		} else {
			if (phone.length == 10) {
				for (var i=0; i < phone.length; i++) {
					var letter = phone.charAt(i).toLowerCase();
					if (validnums.indexOf(letter) == -1){
						errorMessageList[MessageHelper.messages['INVALID_PHONE_NUMBER']]= form.send_message_phone_number.id;
						break;
					}
				}
			} else {
				errorMessageList[MessageHelper.messages['INVALID_PHONE_NUMBER']]= form.send_message_phone_number.id;
			}
		}
//Fix for Defect Id - 722 - End		
		var count = 0;
		var errArr = new Array();
		var idArr = new Array();
		var firstElem = null;
		Util.hidePageErrorMsgs();
		for(i in errorMessageList) {
			errArr.push(i);
			if(errArr.length ==1) {
				firstElem = errorMessageList[i];
			}
			//idArr.push(errors[i]);
			count++;
			dojo.addClass(errorMessageList[i], "fn_valid_mandatory error");
			var errorDiv = dojo.create("div",{innerHTML:i},errorMessageList[i],"after");
			dojo.attr(errorDiv, {"class": "inlineError"});
		}
		if(count>0) {
			dojo.byId(firstElem).focus();
			return;
		} else {
			form.submit();
		}
	}
};

var Misc = {
	setLogonFocus:function(){
		if(dojo.byId("shopLogonDiv")!=null){
			dojo.byId("shopLogonDiv").focus();		
		}else{
			console.debug("the id shopLogonDiv is not found/loaded")
		}
		
	},
	addURLParams:function(url,form){
		var params = form.emailSavings.value;
		if(params != "Enter your email"){
			url+= '&emailSavings='+params;
			Page.redirect(url);
		}else{
			Page.redirect(url);
		}
	}
};
